您的位置:首页 > 技术中心 > 前端框架 >

探索 Node.js 源码,详解cjs 模块的加载过程

时间:2022-09-07 20:13

node.js极速入门课程:进入学习

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

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

没错,require 就是加载 cjs 模块的 API,但 V8 本身是没有 cjs 模块系统的,所以 node 是怎么通过 require找到模块并且加载的呢?【相关教程推荐:nodejs视频教程】

我们今天将对 Node.js 源码进行探索,深入理解 cjs 模块的加载过程。 我们阅读的 node 代码版本为 v17.x:

  • git head :881174e016d6c27b20c70111e6eae2296b6c6293
  • 代码链接:github.com/nodejs/node…

源码阅读

内置模块

为了知道 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 实例:

  1. int Start(int argc, char** argv) {
  2. InitializationResult result = InitializeOncePerProcess(argc, argv);
  3. if (result.early_return) {
  4. return result.exit_code;
  5. }
  6. {
  7. Isolate::CreateParams params;
  8. const std::vector<size_t>* indices = nullptr;
  9. const EnvSerializeInfo* env_info = nullptr;
  10. bool use_node_snapshot =
  11. per_process::cli_options->per_isolate->node_snapshot;
  12. if (use_node_snapshot) {
  13. v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();
  14. if (blob != nullptr) {
  15. params.snapshot_blob = blob;
  16. indices = NodeMainInstance::GetIsolateDataIndices();
  17. env_info = NodeMainInstance::GetEnvSerializeInfo();
  18. }
  19. }
  20. uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
  21. NodeMainInstance main_instance(&params,
  22. uv_default_loop(),
  23. per_process::v8_platform.Platform(),
  24. result.args,
  25. result.exec_args,
  26. indices);
  27. result.exit_code = main_instance.Run(env_info);
  28. }
  29. TearDownOncePerProcess();
  30. return result.exit_code;
  31. }

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

  1. int NodeMainInstance::Run(const EnvSerializeInfo* env_info) {
  2. Locker locker(isolate_);
  3. Isolate::Scope isolate_scope(isolate_);
  4. HandleScope handle_scope(isolate_);
  5. int exit_code = 0;
  6. DeleteFnPtr<Environment, FreeEnvironment> env =
  7. CreateMainEnvironment(&exit_code, env_info);
  8. CHECK_NOT_NULL(env);
  9. Context::Scope context_scope(env->context());
  10. Run(&exit_code, env.get());
  11. return exit_code;
  12. }

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

  1. Environment* CreateEnvironment(
  2. IsolateData* isolate_data,
  3. Local<Context> context,
  4. const std::vector<std::string>& args,
  5. const std::vector<std::string>& exec_args,
  6. EnvironmentFlags::Flags flags,
  7. ThreadId thread_id,
  8. std::unique_ptr<InspectorParentHandle> inspector_parent_handle) {
  9. Isolate* isolate = context->GetIsolate();
  10. HandleScope handle_scope(isolate);
  11. Context::Scope context_scope(context);
  12. // TODO(addaleax): This is a much better place for parsing per-Environment
  13. // options than the global parse call.
  14. Environment* env = new Environment(
  15. isolate_data, context, args, exec_args, nullptr, flags, thread_id);
  16. #if HAVE_INSPECTOR
  17. if (inspector_parent_handle) {
  18. env->InitializeInspector(
  19. std::move(static_cast<InspectorParentHandleImpl*>(
  20. inspector_parent_handle.get())->impl));
  21. } else {
  22. env->InitializeInspector({});
  23. }
  24. #endif
  25. if (env->RunBootstrapping().IsEmpty()) {
  26. FreeEnvironment(env);
  27. return nullptr;
  28. }
  29. return env;
  30. }

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

  1. MaybeLocal<Value> Environment::RunBootstrapping() {
  2. EscapableHandleScope scope(isolate_);
  3. CHECK(!has_run_bootstrapping_code());
  4. if (BootstrapInternalLoaders().IsEmpty()) {
  5. return MaybeLocal<Value>();
  6. }
  7. Local<Value> result;
  8. if (!BootstrapNode().ToLocal(&result)) {
  9. return MaybeLocal<Value>();
  10. }
  11. // Make sure that no request or handle is created during bootstrap -
  12. // if necessary those should be done in pre-execution.
  13. // Usually, doing so would trigger the checks present in the ReqWrap and
  14. // HandleWrap classes, so this is only a consistency check.
  15. CHECK(req_wrap_queue()->IsEmpty());
  16. CHECK(handle_wrap_queue()->IsEmpty());
  17. DoneBootstrapping();
  18. return scope.Escape(result);
  19. }

这里的 [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) 则是专门用于内置模块的小型模块系统。

  1. function nativeModuleRequire(id) {
  2. if (id === loaderId) {
  3. return loaderExports;
  4. }
  5. const mod = NativeModule.map.get(id);
  6. // Can't load the internal errors module from here, have to use a raw error.
  7. // eslint-disable-next-line no-restricted-syntax
  8. if (!mod) throw new TypeError(`Missing internal module '${id}'`);
  9. return mod.compileForInternalLoader();
  10. }
  11. const loaderExports = {
  12. internalBinding,
  13. NativeModule,
  14. require: nativeModuleRequire
  15. };
  16. return loaderExports;

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

用户模块

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

  1. int NodeMainInstance::Run(const EnvSerializeInfo* env_info) {
  2. Locker locker(isolate_);
  3. Isolate::Scope isolate_scope(isolate_);
  4. HandleScope handle_scope(isolate_);
  5. int exit_code = 0;
  6. DeleteFnPtr<Environment, FreeEnvironment> env =
  7. CreateMainEnvironment(&exit_code, env_info);
  8. CHECK_NOT_NULL(env);
  9. Context::Scope context_scope(env->context());
  10. Run(&exit_code, env.get());
  11. return exit_code;
  12. }

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

  1. void NodeMainInstance::Run(int* exit_code, Environment* env) {
  2. if (*exit_code == 0) {
  3. LoadEnvironment(env, StartExecutionCallback{});
  4. *exit_code = SpinEventLoop(env).FromMaybe(1);
  5. }
  6. ResetStdio();
  7. // TODO(addaleax): Neither NODE_SHARED_MODE nor HAVE_INSPECTOR really
  8. // make sense here.
  9. #if HAVE_INSPECTOR && defined(__POSIX__) && !defined(NODE_SHARED_MODE)
  10. struct sigaction act;
  11. memset(&act, 0, sizeof(act));
  12. for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
  13. if (nr == SIGKILL || nr == SIGSTOP || nr == SIGPROF)
  14. continue;
  15. act.sa_handler = (nr == SIGPIPE) ? SIG_IGN : SIG_DFL;
  16. CHECK_EQ(0, sigaction(nr, &act, nullptr));
  17. }
  18. #endif
  19. #if defined(LEAK_SANITIZER)
  20. __lsan_do_leak_check();
  21. #endif
  22. }

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

  1. MaybeLocal<Value> LoadEnvironment(
  2. Environment* env,
  3. StartExecutionCallback cb) {
  4. env->InitializeLibuv();
  5. env->InitializeDiagnostics();
  6. return StartExecution(env, cb);
  7. }

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

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

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) 内的代码:

  1. 'use strict';
  2. const {
  3. prepareMainThreadExecution
  4. } = require('internal/bootstrap/pre_execution');
  5. prepareMainThreadExecution(true);
  6. markBootstrapComplete();
  7. // Note: this loads the module through the ESM loader if the module is
  8. // determined to be an ES module. This hangs from the CJS module loader
  9. // because we currently allow monkey-patching of the module loaders
  10. // in the preloaded scripts through require('module').
  11. // runMain here might be monkey-patched by users in --require.
  12. // XXX: the monkey-patchability here should probably be deprecated.
  13. require('internal/modules/cjs/loader').Module.runMain(process.argv[1]);

所谓的包装 function 并传入 require,伪代码如下:

  1. (function(require, /* 其他入参 */) {
  2. // 这里是 internal/main/run_main_module.js 的文件内容
  3. })();

所以这里是通过内置模块require 函数加载了 [lib/internal/modules/cjs/loader.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L172) 导出的 Module 对象上的 runMain 方法,不过我们在 loader.js 中并没有发现 runMain 函数,其实这个函数是在 [lib/internal/bootstrap/pre_execution.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/pre_execution.js#L428) 中被定义到 Module 对象上的:

  1. function initializeCJSLoader() {
  2. const CJSLoader = require('internal/modules/cjs/loader');
  3. if (!noGlobalSearchPaths) {
  4. CJSLoader.Module._initPaths();
  5. }
  6. // TODO(joyeecheung): deprecate this in favor of a proper hook?
  7. CJSLoader.Module.runMain =
  8. require('internal/modules/run_main').executeUserEntryPoint;
  9. }

[lib/internal/modules/run_main.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/run_main.js#L74) 中找到 executeUserEntryPoint 方法:

  1. function executeUserEntryPoint(main = process.argv[1]) {
  2. const resolvedMain = resolveMainPath(main);
  3. const useESMLoader = shouldUseESMLoader(resolvedMain);
  4. if (useESMLoader) {
  5. runMainESM(resolvedMain || main);
  6. } else {
  7. // Module._load is the monkey-patchable CJS module loader.
  8. Module._load(main, null, true);
  9. }
  10. }

参数 main 即为我们传入的入口文件 index.js。可以看到,index.js 作为一个 cjs 模块应该被 Module._load 加载,那么 _load干了些什么呢?这个函数是 cjs 模块加载过程中最重要的一个函数,值得仔细阅读:

  1. // `_load` 函数检查请求文件的缓存
  2. // 1. 如果模块已经存在,返回已缓存的 exports 对象
  3. // 2. 如果模块是内置模块,通过调用 `NativeModule.prototype.compileForPublicLoader()`
  4. // 获取内置模块的 exports 对象,compileForPublicLoader 函数是有白名单的,只能获取公开
  5. // 内置模块的 exports。
  6. // 3. 以上两者皆为否,创建新的 Module 对象并保存到缓存中,然后通过它加载文件并返回其 exports。
  7. // request:请求的模块,比如 `fs`,`./another-module`,'@pipcook/core' 等
  8. // parent:父模块,如在 `a.js` 中 `require('b.js')`,那么这里的 request 为 'b.js',
  9. parent 为 `a.js` 对应的 Module 对象
  10. // isMain: 除入口文件为 `true` 外,其他模块都为 `false`
  11. Module._load = function(request, parent, isMain) {
  12. let relResolveCacheIdentifier;
  13. if (parent) {
  14. debug('Module._load REQUEST %s parent: %s', request, parent.id);
  15. // relativeResolveCache 是模块路径缓存,
  16. // 用于加速父模块所在目录下的所有模块请求当前模块时
  17. // 可以直接查询到实际路径,而不需要通过 _resolveFilename 查找文件
  18. relResolveCacheIdentifier = `${parent.path}\x00${request}`;
  19. const filename = relativeResolveCache[relResolveCacheIdentifier];
  20. if (filename !== undefined) {
  21. const cachedModule = Module._cache[filename];
  22. if (cachedModule !== undefined) {
  23. updateChildren(parent, cachedModule, true);
  24. if (!cachedModule.loaded)
  25. return getExportsForCircularRequire(cachedModule);
  26. return cachedModule.exports;
  27. }
  28. delete relativeResolveCache[relResolveCacheIdentifier];
  29. }
  30. }
  31. // 尝试查找模块文件路径,找不到模块抛出异常
  32. const filename = Module._resolveFilename(request, parent, isMain);
  33. // 如果是内置模块,从 `NativeModule` 加载
  34. if (StringPrototypeStartsWith(filename, 'node:')) {
  35. // Slice 'node:' prefix
  36. const id = StringPrototypeSlice(filename, 5);
  37. const module = loadNativeModule(id, request);
  38. if (!module?.canBeRequiredByUsers) {
  39. throw new ERR_UNKNOWN_BUILTIN_MODULE(filename);
  40. }
  41. return module.exports;
  42. }
  43. // 如果缓存中已存在,将当前模块 push 到父模块的 children 字段
  44. const cachedModule = Module._cache[filename];
  45. if (cachedModule !== undefined) {
  46. updateChildren(parent, cachedModule, true);
  47. // 处理循环引用
  48. if (!cachedModule.loaded) {
  49. const parseCachedModule = cjsParseCache.get(cachedModule);
  50. if (!parseCachedModule || parseCachedModule.loaded)
  51. return getExportsForCircularRequire(cachedModule);
  52. parseCachedModule.loaded = true;
  53. } else {
  54. return cachedModule.exports;
  55. }
  56. }
  57. // 尝试从内置模块加载
  58. const mod = loadNativeModule(filename, request);
  59. if (mod?.canBeRequiredByUsers) return mod.exports;
  60. // Don't call updateChildren(), Module constructor already does.
  61. const module = cachedModule || new Module(filename, parent);
  62. if (isMain) {
  63. process.mainModule = module;
  64. module.id = '.';
  65. }
  66. // 将 module 对象加入缓存
  67. Module._cache[filename] = module;
  68. if (parent !== undefined) {
  69. relativeResolveCache[relResolveCacheIdentifier] = filename;
  70. }
  71. // 尝试加载模块,如果加载失败则删除缓存中的 module 对象,
  72. // 同时删除父模块的 children 内的 module 对象。
  73. let threw = true;
  74. try {
  75. module.load(filename);
  76. threw = false;
  77. } finally {
  78. if (threw) {
  79. delete Module._cache[filename];
  80. if (parent !== undefined) {
  81. delete relativeResolveCache[relResolveCacheIdentifier];
  82. const children = parent?.children;
  83. if (ArrayIsArray(children)) {
  84. const index = ArrayPrototypeIndexOf(children, module);
  85. if (index !== -1) {
  86. ArrayPrototypeSplice(children, index, 1);
  87. }
  88. }
  89. }
  90. } else if (module.exports &&
  91. !isProxy(module.exports) &&
  92. ObjectGetPrototypeOf(module.exports) ===
  93. CircularRequirePrototypeWarningProxy) {
  94. ObjectSetPrototypeOf(module.exports, ObjectPrototype);
  95. }
  96. }
  97. // 返回 exports 对象
  98. return module.exports;
  99. };

module 对象上的 [load](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L963) 函数用于执行一个模块的加载:

  1. Module.prototype.load = function(filename) {
  2. debug('load %j for module %j', filename, this.id);
  3. assert(!this.loaded);
  4. this.filename = filename;
  5. this.paths = Module._nodeModulePaths(path.dirname(filename));
  6. const extension = findLongestRegisteredExtension(filename);
  7. // allow .mjs to be overridden
  8. if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs'])
  9. throw new ERR_REQUIRE_ESM(filename, true);
  10. Module._extensions[extension](this, filename);
  11. this.loaded = true;
  12. const esmLoader = asyncESM.esmLoader;
  13. // Create module entry at load time to snapshot exports correctly
  14. const exports = this.exports;
  15. // Preemptively cache
  16. if ((module?.module === undefined ||
  17. module.module.getStatus() < kEvaluated) &&
  18. !esmLoader.cjsCache.has(this))
  19. esmLoader.cjsCache.set(this, exports);
  20. };

实际的加载动作是在 Module._extensions[extension](this, filename); 中进行的,根据扩展名的不同,会有不同的加载策略:

  • .js:调用 fs.readFileSync 读取文件内容,将文件内容包在 wrapper 中,需要注意的是,这里的 requireModule.prototype.require 而非内置模块的 require 方法。
  1. const wrapper = [
  2. '(function (exports, require, module, __filename, __dirname) { ',
  3. '\n});',
  4. ];
  • .json:调用 fs.readFileSync 读取文件内容,并转换为对象。
  • .node:调用 dlopen 打开 node 扩展。

Module.prototype.require 函数也是调用了静态方法 Module._load实现模块加载的:

  1. Module.prototype.require = function(id) {
  2. validateString(id, 'id');
  3. if (id === '') {
  4. throw new ERR_INVALID_ARG_VALUE('id', id,
  5. 'must be a non-empty string');
  6. }
  7. requireDepth++;
  8. try {
  9. return Module._load(id, this, /* isMain */ false);
  10. } finally {
  11. requireDepth--;
  12. }
  13. };

总结

看到这里,cjs 模块的加载过程已经基本清晰了:

  • 初始化 node,加载 NativeModule,用于加载所有的内置的 js 和 c++ 模块

  • 运行内置模块 run_main

  • run_main 中引入用户模块系统 module

  • 通过 module_load 方法加载入口文件,在加载时通过传入 module.requiremodule.exports 等让入口文件可以正常 require 其他依赖模块并递归让整个依赖树被完整加载。

在清楚了 cjs 模块加载的完整流程之后,我们还可以顺着这条链路阅读其他代码,比如 global 变量的初始化,esModule 的管理方式等,更深入地理解 node 内的各种实现。

更多node相关知识,请访问:nodejs 教程!

以上就是探索 Node.js 源码,详解cjs 模块的加载过程的详细内容,更多请关注gxlsystem.com其它相关文章!

热门排行

今日推荐

热门手游