您现在的位置是:网站首页> 编程资料编程资料

Node.js 源码阅读深入理解cjs模块系统_node.js_

2023-05-24 232人已围观

简介 Node.js 源码阅读深入理解cjs模块系统_node.js_

前言

相信大家都知道如何在 Node.js 中加载一个模块:

const fs = require('fs'); const express = require('express'); const anotherModule = require('./another-module'); 

没错,require 就是加载 cjs 模块的 API,但 V8 本身是没有 cjs 模块系统的,所以 node 是怎么通过 require找到模块并且加载的呢?我们今天将对 Node.js 源码进行探索,深入理解 cjs 模块的加载过程。 我们阅读的 node 代码版本为 v17.x:

源码阅读

内置模块

为了知道 require 的工作逻辑,我们需要先了解内置模块是如何被加载到 node 中的(诸如 'fs','path','child_process',其中也包括一些无法被用户引用的内部模块),准备好代码之后,我们首先要从 node 启动开始阅读。 node 的 main 函数在 [src/node_main.cc](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main.cc#L105) 内,通过调用方法 [node::Start](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L1134) 来启动一个 node 实例:

int Start(int argc, char** argv) { InitializationResult result = InitializeOncePerProcess(argc, argv); if (result.early_return) { return result.exit_code; } { Isolate::CreateParams params; const std::vector* indices = nullptr; const EnvSerializeInfo* env_info = nullptr; bool use_node_snapshot = per_process::cli_options->per_isolate->node_snapshot; if (use_node_snapshot) { v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob(); if (blob != nullptr) { params.snapshot_blob = blob; indices = NodeMainInstance::GetIsolateDataIndices(); env_info = NodeMainInstance::GetEnvSerializeInfo(); } } uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME); NodeMainInstance main_instance(¶ms, uv_default_loop(), per_process::v8_platform.Platform(), result.args, result.exec_args, indices); result.exit_code = main_instance.Run(env_info); } TearDownOncePerProcess(); return result.exit_code; } 

 这里创建了事件循环,且创建了一个 NodeMainInstance 的实例 main_instance 并调用了它的 Run 方法:

int NodeMainInstance::Run(const EnvSerializeInfo* env_info) { Locker locker(isolate_); Isolate::Scope isolate_scope(isolate_); HandleScope handle_scope(isolate_); int exit_code = 0; DeleteFnPtr env = CreateMainEnvironment(&exit_code, env_info); CHECK_NOT_NULL(env); Context::Scope context_scope(env->context()); Run(&exit_code, env.get()); return exit_code; } 

Run 方法中调用 [CreateMainEnvironment](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main_instance.cc#L170) 来创建并初始化环境:

Environment* CreateEnvironment( IsolateData* isolate_data, Local context, const std::vector& args, const std::vector& exec_args, EnvironmentFlags::Flags flags, ThreadId thread_id, std::unique_ptr inspector_parent_handle) { Isolate* isolate = context->GetIsolate(); HandleScope handle_scope(isolate); Context::Scope context_scope(context); // TODO(addaleax): This is a much better place for parsing per-Environment // options than the global parse call. Environment* env = new Environment( isolate_data, context, args, exec_args, nullptr, flags, thread_id); #if HAVE_INSPECTOR if (inspector_parent_handle) { env->InitializeInspector( std::move(static_cast( inspector_parent_handle.get())->impl)); } else { env->InitializeInspector({}); } #endif if (env->RunBootstrapping().IsEmpty()) { FreeEnvironment(env); return nullptr; } return env; } 

创建 Environment 对象 env 并调用其 [RunBootstrapping](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L398) 方法:

MaybeLocal Environment::RunBootstrapping() { EscapableHandleScope scope(isolate_); CHECK(!has_run_bootstrapping_code()); if (BootstrapInternalLoaders().IsEmpty()) { return MaybeLocal(); } Local result; if (!BootstrapNode().ToLocal(&result)) { return MaybeLocal(); } // Make sure that no request or handle is created during bootstrap - // if necessary those should be done in pre-execution. // Usually, doing so would trigger the checks present in the ReqWrap and // HandleWrap classes, so this is only a consistency check. CHECK(req_wrap_queue()->IsEmpty()); CHECK(handle_wrap_queue()->IsEmpty()); DoneBootstrapping(); return scope.Escape(result); } 

这里的 [BootstrapInternalLoaders](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L298) 实现了 node 模块加载过程中非常重要的一步: 通过包装并执行 [internal/bootstrap/loaders.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L326) 获取内置模块的 [nativeModulerequire](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L332) 函数用于加载内置的 js 模块,获取 [internalBinding](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L164) 用于加载内置的 C++ 模块,[NativeModule](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L191) 则是专门用于内置模块的小型模块系统。

function nativeModuleRequire(id) { if (id === loaderId) { return loaderExports; } const mod = NativeModule.map.get(id); // Can't load the internal errors module from here, have to use a raw error. // eslint-disable-next-line no-restricted-syntax if (!mod) throw new TypeError(`Missing internal module '${id}'`); return mod.compileForInternalLoader(); } const loaderExports = { internalBinding, NativeModule, require: nativeModuleRequire }; return loaderExports; 

需要注意的是,这个 require 函数只会被用于内置模块的加载,用户模块的加载并不会用到它。(这也是为什么我们通过打印 require('module')._cache 可以看到所有用户模块,却看不到 fs 等内置模块的原因,因为两者的加载和缓存维护方式并不一样)。

用户模块

接下来让我们把目光移回到 [NodeMainInstance::Run](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main_instance.cc#L127) 函数:

int NodeMainInstance::Run(const EnvSerializeInfo* env_info) { Locker locker(isolate_); Isolate::Scope isolate_scope(isolate_); HandleScope handle_scope(isolate_); int exit_code = 0; DeleteFnPtr env = CreateMainEnvironment(&exit_code, env_info); CHECK_NOT_NULL(env); Context::Scope context_scope(env->context()); Run(&exit_code, env.get()); return exit_code; } 

我们已经通过 CreateMainEnvironment 函数创建好了一个 env 对象,这个 Environment 实例已经有了一个模块系统 NativeModule 用于维护内置模块。 然后代码会运行到 Run 函数的另一个重载版本

void NodeMainInstance::Run(int* exit_code, Environment* env) { if (*exit_code == 0) { LoadEnvironment(env, StartExecutionCallback{}); *exit_code = SpinEventLoop(env).FromMaybe(1); } ResetStdio(); // TODO(addaleax): Neither NODE_SHARED_MODE nor HAVE_INSPECTOR really // make sense here. #if HAVE_INSPECTOR && defined(__POSIX__) && !defined(NODE_SHARED_MODE) struct sigaction act; memset(&act, 0, sizeof(act)); for (unsigned nr = 1; nr < kMaxSignal; nr += 1) { if (nr == SIGKILL || nr == SIGSTOP || nr == SIGPROF) continue; act.sa_handler = (nr == SIGPIPE) ? SIG_IGN : SIG_DFL; CHECK_EQ(0, sigaction(nr, &act, nullptr)); } #endif #if defined(LEAK_SANITIZER) __lsan_do_leak_check(); #endif } 

在这里调用 [LoadEnvironment](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/api/environment.cc#L403)

MaybeLocal LoadEnvironment( Environment* env, StartExecutionCallback cb) { env->InitializeLibuv(); env->InitializeDiagnostics(); return StartExecution(env, cb); } 

然后执行 [StartExecution](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L455)

MaybeLocal StartExecution(Environment* env, StartExecutionCallback cb) { // 已省略其他运行方式,我们只看 `node index.js` 这种情况,不影响我们理解模块系统 if (!first_argv.empty() && first_argv != "-") { return StartExecution(env, "internal/main/run_main_module"); } } 

StartExecution(env, "internal/main/run_main_module")这个调用中,我们会包装一个 function,并传入刚刚从 loaders 中导出的 require 函数,并运行 [lib/internal/main/run_main_module.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/main/run_main_module.js) 内的代码:

'use strict'; const { prepareMainThreadExecution } = require('internal/bootstrap/pre_execution'); prepareMainThreadExecution(true); markBootstrapComplete(); // Note: this lo
                
                

-六神源码网