讀 Node-js 源碼深入理解 cjs 模塊系統
本文將對 Node.js 源碼進行探索,深入理解 cjs 模塊的加載過程。
相信大家都知道如何在 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:
git head :881174e016d6c27b20c70111e6eae2296b6c6293
代碼鏈接:https://github.com/nodejs/node/tree/881174e016d6c27b20c70111e6eae2296b6c6293
內置模塊
爲了知道 require
的工作邏輯,我們需要先了解內置模塊是如何被加載到 node 中的 (諸如'fs','path','child_process',也包括無法被用戶引用的內部模塊),準備好代碼之後,我們首先要從 node 啓動開始閱讀。
node 的 main 函數在 src/node_main.cc
內,通過調用 API node::Start
來啓動一個 node 實例:
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
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<size_t>* 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 方法:
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<Environment, FreeEnvironment> 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
來創建並初始化環境:
CreateMainEnvironment
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main_instance.cc#L170
Environment* CreateEnvironment(
IsolateData* isolate_data,
Local<Context> context,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args,
EnvironmentFlags::Flags flags,
ThreadId thread_id,
std::unique_ptr<InspectorParentHandle> 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<InspectorParentHandleImpl*>(
inspector_parent_handle.get())->impl));
} else {
env->InitializeInspector({});
}
#endif
if (env->RunBootstrapping().IsEmpty()) {
FreeEnvironment(env);
return nullptr;
}
return env;
}
通過創建 Environment
對象 env
並調用其 RunBootstrapping
方法:
RunBootstrapping
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L398
MaybeLocal<Value> Environment::RunBootstrapping() {
EscapableHandleScope scope(isolate_);
CHECK(!has_run_bootstrapping_code());
if (BootstrapInternalLoaders().IsEmpty()) {
return MaybeLocal<Value>();
}
Local<Value> result;
if (!BootstrapNode().ToLocal(&result)) {
return MaybeLocal<Value>();
}
// 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
實現了 node 模塊加載過程中非常重要的一步:
通過包裝並執行 internal/bootstrap/loaders.js
獲取內置模塊的 nativeModulerequire
函數用於加載內置的 js 模塊,獲取 internalBinding
用於加載內置的 C++ 模塊,NativeModule
則是專門用於內置模塊的小型模塊系統。
BootstrapInternalLoaders
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L298
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#L326
nativeModulerequire
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L332
internalBinding
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L164
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
函數:
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<Environment, FreeEnvironment> 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
函數的另一個重載版本:
重載版本地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main_instance.cc#L142
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
:
LoadEnvironment
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/api/environment.cc#L403
MaybeLocal<Value> LoadEnvironment(
Environment* env,
StartExecutionCallback cb) {
env->InitializeLibuv();
env->InitializeDiagnostics();
return StartExecution(env, cb);
}
然後執行 StartExecution
:
StartExecution
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L455
MaybeLocal<Value> 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
內的代碼:
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 loads the module through the ESM loader if the module is
// determined to be an ES module. This hangs from the CJS module loader
// because we currently allow monkey-patching of the module loaders
// in the preloaded scripts through require('module').
// runMain here might be monkey-patched by users in --require.
// XXX: the monkey-patchability here should probably be deprecated.
require('internal/modules/cjs/loader').Module.runMain(process.argv[1]);
所謂的包裝 function 並傳入 require
,僞代碼如下:
(function(require, /* 其他入參 */) {
// 這裏是 internal/main/run_main_module.js 的文件內容
})();
所以這裏是通過內置模塊的 require
函數加載了 lib/internal/modules/cjs/loader.js
導出的 Module 對象上的 runMain
方法,不過我們在 loader.js
中並沒有發現 runMain
函數,其實這個函數是在 lib/internal/bootstrap/pre_execution.js
中被定義到 Module
對象上的:
lib/internal/modules/cjs/loader.js
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L172
lib/internal/bootstrap/pre_execution.js
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/pre_execution.js#L428
function initializeCJSLoader() {
const CJSLoader = require('internal/modules/cjs/loader');
if (!noGlobalSearchPaths) {
CJSLoader.Module._initPaths();
}
// TODO(joyeecheung): deprecate this in favor of a proper hook?
CJSLoader.Module.runMain =
require('internal/modules/run_main').executeUserEntryPoint;
}
在 lib/internal/modules/run_main.js
中找到 executeUserEntryPoint
方法:
lib/internal/modules/run_main.js
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/run_main.js#L74
function executeUserEntryPoint(main = process.argv[1]) {
const resolvedMain = resolveMainPath(main);
const useESMLoader = shouldUseESMLoader(resolvedMain);
if (useESMLoader) {
runMainESM(resolvedMain || main);
} else {
// Module._load is the monkey-patchable CJS module loader.
Module._load(main, null, true);
}
}
參數 main
即爲我們傳入的入口文件 index.js
。可以看到,index.js
作爲一個 cjs 模塊應該被 Module._load
加載,那麼 _load
幹了些什麼呢?這個函數是 cjs 模塊加載過程中最重要的一個函數,值得仔細閱讀:
// `_load` 函數檢查請求文件的緩存
// 1. 如果模塊已經存在,返回已緩存的 exports 對象
// 2. 如果模塊是內置模塊,通過調用 `NativeModule.prototype.compileForPublicLoader()`
// 獲取內置模塊的 exports 對象,compileForPublicLoader 函數是有白名單的,只能獲取公開
// 內置模塊的 exports。
// 3. 以上兩者皆爲否,創建新的 Module 對象並保存到緩存中,然後通過它加載文件並返回其 exports。
// request:請求的模塊,比如 `fs`,`./another-module`,'@pipcook/core' 等
// parent:父模塊,如在 `a.js` 中 `require('b.js')`,那麼這裏的 request 爲 'b.js',
parent 爲 `a.js` 對應的 Module 對象
// isMain: 除入口文件爲 `true` 外,其他模塊都爲 `false`
Module._load = function(request, parent, isMain) {
let relResolveCacheIdentifier;
if (parent) {
debug('Module._load REQUEST %s parent: %s', request, parent.id);
// relativeResolveCache 是模塊路徑緩存,
// 用於加速父模塊所在目錄下的所有模塊請求當前模塊時
// 可以直接查詢到實際路徑,而不需要通過 _resolveFilename 查找文件
relResolveCacheIdentifier = `${parent.path}\x00${request}`;
const filename = relativeResolveCache[relResolveCacheIdentifier];
if (filename !== undefined) {
const cachedModule = Module._cache[filename];
if (cachedModule !== undefined) {
updateChildren(parent, cachedModule, true);
if (!cachedModule.loaded)
return getExportsForCircularRequire(cachedModule);
return cachedModule.exports;
}
delete relativeResolveCache[relResolveCacheIdentifier];
}
}
// 嘗試查找模塊文件路徑,找不到模塊拋出異常
const filename = Module._resolveFilename(request, parent, isMain);
// 如果是內置模塊,從 `NativeModule` 加載
if (StringPrototypeStartsWith(filename, 'node:')) {
// Slice 'node:' prefix
const id = StringPrototypeSlice(filename, 5);
const module = loadNativeModule(id, request);
if (!module?.canBeRequiredByUsers) {
throw new ERR_UNKNOWN_BUILTIN_MODULE(filename);
}
return module.exports;
}
// 如果緩存中已存在,將當前模塊 push 到父模塊的 children 字段
const cachedModule = Module._cache[filename];
if (cachedModule !== undefined) {
updateChildren(parent, cachedModule, true);
// 處理循環引用
if (!cachedModule.loaded) {
const parseCachedModule = cjsParseCache.get(cachedModule);
if (!parseCachedModule || parseCachedModule.loaded)
return getExportsForCircularRequire(cachedModule);
parseCachedModule.loaded = true;
} else {
return cachedModule.exports;
}
}
// 嘗試從內置模塊加載
const mod = loadNativeModule(filename, request);
if (mod?.canBeRequiredByUsers) return mod.exports;
// Don't call updateChildren(), Module constructor already does.
const module = cachedModule || new Module(filename, parent);
if (isMain) {
process.mainModule = module;
module.id = '.';
}
// 將 module 對象加入緩存
Module._cache[filename] = module;
if (parent !== undefined) {
relativeResolveCache[relResolveCacheIdentifier] = filename;
}
// 嘗試加載模塊,如果加載失敗則刪除緩存中的 module 對象,
// 同時刪除父模塊的 children 內的 module 對象。
let threw = true;
try {
module.load(filename);
threw = false;
} finally {
if (threw) {
delete Module._cache[filename];
if (parent !== undefined) {
delete relativeResolveCache[relResolveCacheIdentifier];
const children = parent?.children;
if (ArrayIsArray(children)) {
const index = ArrayPrototypeIndexOf(children, module);
if (index !== -1) {
ArrayPrototypeSplice(children, index, 1);
}
}
}
} else if (module.exports &&
!isProxy(module.exports) &&
ObjectGetPrototypeOf(module.exports) ===
CircularRequirePrototypeWarningProxy) {
ObjectSetPrototypeOf(module.exports, ObjectPrototype);
}
}
// 返回 exports 對象
return module.exports;
};
module
對象上的 load
函數用於執行一個模塊的加載:
load
地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L963
Module.prototype.load = function(filename) {
debug('load %j for module %j', filename, this.id);
assert(!this.loaded);
this.filename = filename;
this.paths = Module._nodeModulePaths(path.dirname(filename));
const extension = findLongestRegisteredExtension(filename);
// allow .mjs to be overridden
if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs'])
throw new ERR_REQUIRE_ESM(filename, true);
Module._extensions[extension](this, filename);
this.loaded = true;
const esmLoader = asyncESM.esmLoader;
// Create module entry at load time to snapshot exports correctly
const exports = this.exports;
// Preemptively cache
if ((module?.module === undefined ||
module.module.getStatus() < kEvaluated) &&
!esmLoader.cjsCache.has(this))
esmLoader.cjsCache.set(this, exports);
};
實際的加載動作是在 Module._extensions[extension](this, filename);
中進行的,根據擴展名的不同,會有不同的加載策略:
-
.js:調用
fs.readFileSync
讀取文件內容,將文件內容包在 wrapper 中,需要注意的是,這裏的require
是Module.prototype.require
而非內置模塊的require
方法。const wrapper = [ '(function (exports, require, module, __filename, __dirname) { ', '\n});', ];
-
.json:調用
fs.readFileSync
讀取文件內容,並轉換爲對象。 -
.node:調用
dlopen
打開 node 擴展。
.js 地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L1104
.json 地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L1152
.node 地址:https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L1170
而 Module.prototype.require
函數也是調用了靜態方法 Module._load
實現模塊加載的:
Module.prototype.require = function(id) {
validateString(id, 'id');
if (id === '') {
throw new ERR_INVALID_ARG_VALUE('id', id,
'must be a non-empty string');
}
requireDepth++;
try {
return Module._load(id, this, /* isMain */ false);
} finally {
requireDepth--;
}
};
看到這裏,cjs 模塊的加載過程已經基本清晰了:
-
初始化 node,加載 NativeModule,用於加載所有的內置的 js 和 c++ 模塊
-
運行內置模塊
run_main
-
在
run_main
中引入用戶模塊系統module
-
通過
module
的_load
方法加載入口文件,在加載時通過傳入module.require
和module.exports
等讓入口文件可以正常require
其他依賴模塊並遞歸讓整個依賴樹被完整加載。
在清楚了 cjs 模塊加載的完整流程之後,我們還可以順着這條鏈路閱讀其他代碼,比如 global
變量的初始化,esModule 的管理方式等,更深入地理解 node 內的各種實現。
作者 | 周飛宇 (牟牟)
編輯 | 橙子君
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/E9RSRWMo1_9_2W3yMzq95Q