Node.js 采用 CommonJS 模块化规范,让 JavaScript 成为了一门真正能够适应大型工程的语言,在 Node.js 中使用模块非常简单,通过 require 一些想要的包,然后需要产出的代码通过 module.exports 导出。但是除了 require 和 exports 以外,关于 NodeJs 的模块加载机制还有哪些需要了解呢?它的源码是如何实现的呢?
模块分类
- C/C++ 模块:也叫 built-in 模块,一般我们不直接调用,而是在 native 模块中调用,然后我们再 require
native 模块,比如我们在 Node.js 中常用的 buffer,fs,os 等 native 模块,其底层都有调用 built-in 模块。 - native 模块:Node 自带模块,比如我们在 Node.js 中常用的 buffer,fs,os 等都是 native 模块,这些模块不需要 npm install 便可以直接使用。
- 第三方模块:非 Node.js 源码自带的模块都可以统称第三方模块,比如 express,webpack,koa等等,第三方模块又分为以下几种:
- 1. JavaScript 模块,这是最常见的,我们开发的时候一般都写的是 JavaScript 模块
- 2. JSON 模块,这个很简单,就是一个 JSON 文件
- 3. C/C++ 扩展模块,使用 C/C++ 编写,编译之后的后缀名为 .node
模块加载前的准备
在看 node源码 的过程可以知道,当我们在执行 node app.js 这个命令时,整个模块的启动流程如下(其中我们只关心模块加载主流程的源码,其它细节忽略):
- node 命令主入口(src/node_main.cc)
int main(int argc, char* argv[]) {
/*...*/
//src/node_main.cc会调用 src/node.cc 中的 Start 函数
return node::Start(argc, argv);
}
- 加载第一个 js 文件(src/node.cc)
inline int Start(Isolate* isolate, IsolateData* isolate_data,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args) {
Environment::AsyncCallbackScope callback_scope(&env);
env.async_hooks()->push_async_ids(1, 0);
// Start 函数会调用 LoadEnvironment 函数
LoadEnvironment(&env);
env.async_hooks()->pop_async_id(1);
}
void LoadEnvironment(Environment* env) {
// 这是我们加载的第一个 js 文件(internal/bootstrap/node.js)
Local<String> node_name =
FIXED_ONE_BYTE_STRING(env->isolate(), "internal/bootstrap/node.js");
MaybeLocal<Function> node_bootstrapper =
GetBootstrapper(env, NodeBootstrapperSource(env), node_name);
/*...*/
// 执行 internal/bootstrap/node.js 代码
if (!ExecuteBootstrapper(env, node_bootstrapper.ToLocalChecked(),
arraysize(node_bootstrapper_args),
node_bootstrapper_args,
&bootstrapped_node)) {
return;
}
}
static bool ExecuteBootstrapper(Environment* env, Local<Function> bootstrapper,
int argc, Local<Value> argv[],
Local<Value>* out) {
// 将相关环境变量传入执行 bootstrapper 代码
bool ret = bootstrapper->Call(
env->context(</