Node.js?源碼閱讀深入理解cjs模塊系統(tǒng)
前言
相信大家都知道如何在 Node.js 中加載一個模塊:
const fs = require('fs');
const express = require('express');
const anotherModule = require('./another-module');
沒錯,require 就是加載 cjs 模塊的 API,但 V8 本身是沒有 cjs 模塊系統(tǒng)的,所以 node 是怎么通過 require找到模塊并且加載的呢?我們今天將對 Node.js 源碼進(jìn)行探索,深入理解 cjs 模塊的加載過程。 我們閱讀的 node 代碼版本為 v17.x:
- git head :881174e016d6c27b20c70111e6eae2296b6c6293
- 代碼鏈接:github.com/nodejs/node…
源碼閱讀
內(nèi)置模塊
為了知道 require 的工作邏輯,我們需要先了解內(nèi)置模塊是如何被加載到 node 中的(諸如 'fs','path','child_process',其中也包括一些無法被用戶引用的內(nèi)部模塊),準(zhǔn)備好代碼之后,我們首先要從 node 啟動開始閱讀。 node 的 main 函數(shù)在 [src/node_main.cc](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main.cc#L105) 內(nèi),通過調(diào)用方法 [node::Start](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L1134) 來啟動一個 node 實(shí)例:
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;
}
這里創(chuàng)建了事件循環(huán),且創(chuàng)建了一個 NodeMainInstance 的實(shí)例 main_instance 并調(diào)用了它的 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<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 方法中調(diào)用 [CreateMainEnvironment](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main_instance.cc#L170) 來創(chuàng)建并初始化環(huán)境:
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;
}
創(chuàng)建 Environment 對象 env 并調(diào)用其 [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](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L298) 實(shí)現(xiàn)了 node 模塊加載過程中非常重要的一步: 通過包裝并執(zhí)行 [internal/bootstrap/loaders.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L326) 獲取內(nèi)置模塊的 [nativeModulerequire](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L332) 函數(shù)用于加載內(nèi)置的 js 模塊,獲取 [internalBinding](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L164) 用于加載內(nèi)置的 C++ 模塊,[NativeModule](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L191) 則是專門用于內(nèi)置模塊的小型模塊系統(tǒng)。
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 函數(shù)只會被用于內(nèi)置模塊的加載,用戶模塊的加載并不會用到它。(這也是為什么我們通過打印 require('module')._cache 可以看到所有用戶模塊,卻看不到 fs 等內(nèi)置模塊的原因,因?yàn)閮烧叩募虞d和緩存維護(hù)方式并不一樣)。
用戶模塊
接下來讓我們把目光移回到 [NodeMainInstance::Run](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main_instance.cc#L127) 函數(shù):
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;
}
我們已經(jīng)通過 CreateMainEnvironment 函數(shù)創(chuàng)建好了一個 env 對象,這個 Environment 實(shí)例已經(jīng)有了一個模塊系統(tǒng) NativeModule 用于維護(hù)內(nèi)置模塊。 然后代碼會運(yùn)行到 Run 函數(shù)的另一個重載版本:
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
}
在這里調(diào)用 [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);
}
然后執(zhí)行 [StartExecution](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L455):
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
// 已省略其他運(yùn)行方式,我們只看 `node index.js` 這種情況,不影響我們理解模塊系統(tǒng)
if (!first_argv.empty() && first_argv != "-") {
return StartExecution(env, "internal/main/run_main_module");
}
}
在 StartExecution(env, "internal/main/run_main_module")這個調(diào)用中,我們會包裝一個 function,并傳入剛剛從 loaders 中導(dǎo)出的 require 函數(shù),并運(yùn)行 [lib/internal/main/run_main_module.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/main/run_main_module.js) 內(nèi)的代碼:
'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, /* 其他入?yún)?*/) {
// 這里是 internal/main/run_main_module.js 的文件內(nèi)容
})();
所以這里是通過內(nèi)置模塊的 require 函數(shù)加載了 [lib/internal/modules/cjs/loader.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L172) 導(dǎo)出的 Module 對象上的 runMain 方法,不過我們在 loader.js 中并沒有發(fā)現(xiàn) runMain 函數(shù),其實(shí)這個函數(shù)是在 [lib/internal/bootstrap/pre_execution.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/pre_execution.js#L428) 中被定義到 Module 對象上的:
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](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/run_main.js#L74)
中找到 executeUserEntryPoint 方法:
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);
}
}
參數(shù) main 即為我們傳入的入口文件 index.js??梢钥吹?,index.js 作為一個 cjs 模塊應(yīng)該被 Module._load 加載,那么 _load干了些什么呢?這個函數(shù)是 cjs 模塊加載過程中最重要的一個函數(shù),值得仔細(xì)閱讀:
// `_load` 函數(shù)檢查請求文件的緩存
// 1. 如果模塊已經(jīng)存在,返回已緩存的 exports 對象
// 2. 如果模塊是內(nèi)置模塊,通過調(diào)用 `NativeModule.prototype.compileForPublicLoader()`
// 獲取內(nèi)置模塊的 exports 對象,compileForPublicLoader 函數(shù)是有白名單的,只能獲取公開
// 內(nèi)置模塊的 exports。
// 3. 以上兩者皆為否,創(chuàng)建新的 Module 對象并保存到緩存中,然后通過它加載文件并返回其 exports。
// request:請求的模塊,比如 `fs`,`./another-module`,'@pipcook/core' 等
// parent:父模塊,如在 `a.js` 中 `require('b.js')`,那么這里的 request 為 'b.js',
parent 為 `a.js` 對應(yīng)的 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 是模塊路徑緩存,
// 用于加速父模塊所在目錄下的所有模塊請求當(dāng)前模塊時
// 可以直接查詢到實(shí)際路徑,而不需要通過 _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);
// 如果是內(nèi)置模塊,從 `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;
}
// 如果緩存中已存在,將當(dāng)前模塊 push 到父模塊的 children 字段
const cachedModule = Module._cache[filename];
if (cachedModule !== undefined) {
updateChildren(parent, cachedModule, true);
// 處理循環(huán)引用
if (!cachedModule.loaded) {
const parseCachedModule = cjsParseCache.get(cachedModule);
if (!parseCachedModule || parseCachedModule.loaded)
return getExportsForCircularRequire(cachedModule);
parseCachedModule.loaded = true;
} else {
return cachedModule.exports;
}
}
// 嘗試從內(nèi)置模塊加載
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 內(nèi)的 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](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L963)
函數(shù)用于執(zhí)行一個模塊的加載:
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);
};
實(shí)際的加載動作是在 Module._extensions[extension](this, filename); 中進(jìn)行的,根據(jù)擴(kuò)展名的不同,會有不同的加載策略:
- .js:調(diào)用
fs.readFileSync讀取文件內(nèi)容,將文件內(nèi)容包在 wrapper 中,需要注意的是,這里的require是Module.prototype.require而非內(nèi)置模塊的require方法。
const wrapper = [
'(function (exports, require, module, __filename, __dirname) { ',
'\n});',
];
而 Module.prototype.require 函數(shù)也是調(diào)用了靜態(tài)方法 Module._load實(shí)現(xiàn)模塊加載的:
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--;
}
};
總結(jié)
看到這里,cjs 模塊的加載過程已經(jīng)基本清晰了:
- 初始化 node,加載 NativeModule,用于加載所有的內(nèi)置的 js 和 c++ 模塊
- 運(yùn)行內(nèi)置模塊
run_main - 在
run_main中引入用戶模塊系統(tǒng)module - 通過
module的_load方法加載入口文件,在加載時通過傳入module.require和module.exports等讓入口文件可以正常require其他依賴模塊并遞歸讓整個依賴樹被完整加載。
在清楚了 cjs 模塊加載的完整流程之后,我們還可以順著這條鏈路閱讀其他代碼,比如 global 變量的初始化,esModule 的管理方式等,更深入地理解 node 內(nèi)的各種實(shí)現(xiàn)。
以上就是Node.js 源碼閱讀深入理解cjs模塊系統(tǒng)的詳細(xì)內(nèi)容,更多關(guān)于Node.js cjs模塊系統(tǒng)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
nodejs中express入門和基礎(chǔ)知識點(diǎn)學(xué)習(xí)
這篇文章給大家分享了關(guān)于學(xué)習(xí)nodejs中express入門和基礎(chǔ)知識點(diǎn)內(nèi)容,有興趣的朋友們參考下。2018-09-09
Node.js實(shí)現(xiàn)批量去除BOM文件頭
這篇文章主要介紹了Node.js實(shí)現(xiàn)批量去除BOM文件頭,本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2014-12-12
詳解使用Visual Studio Code對Node.js進(jìn)行斷點(diǎn)調(diào)試
這篇文章主要介紹了詳解使用Visual Studio Code對Node.js進(jìn)行斷點(diǎn)調(diào)試,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09
Node.js?連接?MySql?統(tǒng)計(jì)組件屬性的使用情況解析
這篇文章主要為大家介紹了Node.js?連接?MySql?統(tǒng)計(jì)組件屬性的使用情況解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
nodejs的http和https下載遠(yuǎn)程資源post數(shù)據(jù)實(shí)例
這篇文章主要為大家介紹了nodejs的http和https下載遠(yuǎn)程資源post數(shù)據(jù)實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
詳解使用vscode+es6寫nodejs服務(wù)端調(diào)試配置
本篇文章主要介紹了使用vscode+es6寫nodejs服務(wù)端調(diào)試配置,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09

