module 模块
History
稳定性:2 - 稳定
node:module 模块提供了与 Node.js 模块系统交互的
实用工具。
可以通过以下方式访问:
import module from 'node:module';类:Module
History
CommonJS 模块中的 module 对象是此类的实例。
有关 module 对象,请参阅 CommonJS 文档。
module.builtinModules
History
该列表现在还包含仅前缀的模块。
- 类型:
<string>[]
由 Node.js 提供的所有模块的名称列表。
import { builtinModules } from 'node:module';
console.log(builtinModules.filter((name) => name.startsWith('path')));
// 打印:[ 'path', 'path/posix', 'path/win32' ]要测试模块名称是否对应于内置模块,请使用
module.isBuiltin()。
module.createRequire(filename): voidimport { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
// sibling-module.js 是一个 CommonJS 模块。
const siblingModule = require('./sibling-module');module.findPackageJSON(specifier, base?): void稳定性:1.1 - 活跃开发中
注意:请勿使用此方法尝试确定模块格式。有许多因素会影响 这一判断;package.json 的
type字段是 最不 确定的依据(例如文件扩展名 会覆盖它,而加载器钩子又会覆盖文件扩展名)。
注意:目前这仅利用内置的默认解析器;如果 已注册
resolve自定义钩子,它们不会影响解析结果。 这在未来可能会改变。
/path/to/project
├ packages/
├ bar/
├ bar.js
└ package.json // name = '@foo/bar'
└ qux/
├ node_modules/
└ some-package/
└ package.json // name = 'some-package'
├ qux.js
└ package.json // name = '@foo/qux'
├ main.js
└ package.json // name = '@foo'module.isBuiltin(moduleName): void<string>import { isBuiltin } from 'node:module';
isBuiltin('node:fs'); // true
isBuiltin('fs'); // true
isBuiltin('wss'); // falsemodule.register
History
运行时弃用(DEP0205)。
在启用权限模型的情况下使用此功能需要 传入 --allow-worker。
增加对 WHATWG URL 实例的支持。
module.register(specifier, parentURL?, options?): void稳定性:0 - 已弃用:请改用
module.registerHooks()。
import.meta.url
)解析
specifier
,可以在此处传入该 URL。
默认值:
'data:'注册一个导出 钩子 的模块,这些钩子用于自定义 Node.js 的模块 解析和加载行为。请参阅 自定义钩子。
如果与 权限模型 一起使用,此功能需要 --allow-worker。
module.registerHooks
History
同步和线程内钩子现已进入候选发布阶段。
module.registerHooks(options): void稳定性:1.2 - 候选发布
<Object><Function>
|
<undefined>undefined
。<Function>
|
<undefined>undefined
。注册用于自定义 Node.js 模块解析和加载行为的 钩子。 请参阅 自定义钩子。返回的对象可用于 取消注册钩子。
module.stripTypeScriptTypes
History
移除了 transform 和 sourceMap 选项。
module.stripTypeScriptTypes(code, options?): void稳定性:1.2 - 候选发布
module.stripTypeScriptTypes() 会从 TypeScript 代码中移除类型注解。
可用于在用 vm.runInContext() 或 vm.compileFunction() 运行之前
移除 TypeScript 代码中的类型注解。
默认情况下,如果代码包含需要转换的 TypeScript 特性(如
enum),它将抛出错误。有关更多信息,请参阅 类型移除。
警告:此函数的输出不应被视为在不同 Node.js 版本之间稳定, 因为 TypeScript 解析器会发生变化。
import { stripTypeScriptTypes } from 'node:module';
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code);
console.log(strippedCode);
// 打印:const a = 1;如果提供了 sourceUrl,它将被追加为输出末尾的注释:
import { stripTypeScriptTypes } from 'node:module';
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
console.log(strippedCode);
// 打印:const a = 1\n\n//# sourceURL=source.ts;module.syncBuiltinESMExports(): voidmodule.syncBuiltinESMExports() 方法会更新所有内置
ES 模块 的实时绑定,使其与 CommonJS 导出的属性相匹配。
它不会从 ES 模块 中添加或移除导出名称。
const fs = require('node:fs');
const assert = require('node:assert');
const { syncBuiltinESMExports } = require('node:module');
fs.readFile = newAPI;
delete fs.readFileSync;
function newAPI() {
// ...
}
fs.newAPI = newAPI;
syncBuiltinESMExports();
import('node:fs').then((esmFS) => {
// 它会将现有的 readFile 属性与新值同步
assert.strictEqual(esmFS.readFile, newAPI);
// readFileSync 已从 require 的 fs 中删除
assert.strictEqual('readFileSync' in fs, false);
// syncBuiltinESMExports() 不会从 esmFS 中移除 readFileSync
assert.strictEqual('readFileSync' in esmFS, true);
// syncBuiltinESMExports() 不会添加名称
assert.strictEqual(esmFS.newAPI, undefined);
});模块编译缓存
History
添加用于运行时访问的初始 JavaScript API。
模块编译缓存可以通过 module.enableCompileCache() 方法或
NODE_COMPILE_CACHE=dir 环境变量启用。启用后,
每当 Node.js 编译 CommonJS、ECMAScript 模块或 TypeScript 模块时,它将
使用保存在指定目录中的磁盘 V8 代码缓存 来加速编译。
这可能会减慢模块图的首次加载,但如果模块内容没有变化,
同一模块图的后续加载可能会显著加速。
要清理磁盘上生成的编译缓存,只需删除缓存目录。下次使用
同一目录存储编译缓存时会重新创建该目录。为避免陈旧缓存
占满磁盘,建议使用 os.tmpdir() 下的目录。如果调用
module.enableCompileCache() 启用编译缓存时未指定 directory,
Node.js 将使用 NODE_COMPILE_CACHE=dir 环境变量(如果已设置),
否则默认使用 path.join(os.tmpdir(), 'node-compile-cache')。要查找
正在运行的 Node.js 实例所使用的编译缓存目录,请使用
module.getCompileCacheDir()。
已启用的模块编译缓存可以通过 NODE_DISABLE_COMPILE_CACHE=1
环境变量禁用。当编译缓存导致意外或非预期的
行为时(例如测试覆盖率不够精确),这可能很有用。
目前,当启用编译缓存并重新加载模块时,会立即从编译后的代码生成
代码缓存,但只有在 Node.js 实例即将退出时才会写入磁盘。
这可能会发生变化。如果应用程序希望派生其他 Node.js 实例,
并让它们在父进程退出之前很久就共享缓存,可以使用
module.flushCompileCache() 方法确保累积的代码缓存
已刷新到磁盘。
磁盘上的编译缓存布局属于实现细节,不应 依赖。生成的编译缓存通常只能在相同版本的 Node.js 中重用,不应假定其在不同版本的 Node.js 之间兼容。
默认情况下,当被缓存模块的绝对路径发生变化时, 缓存会失效。要在移动项目目录后仍保持缓存可用, 请启用可移植编译缓存。这样,只要相对于缓存目录的 布局保持不变,以前编译过的模块就可以在不同的目录 位置之间重用。这是尽力而为的。如果 Node.js 无法 计算模块相对于缓存目录的位置,则该模块将不会被 缓存。
可移植缓存也不会按用户划分:在具有 uid 的平台上, 非可移植缓存的子目录会附带创建它的用户的 uid 后缀, 因此只有该用户能找到它;而可移植缓存对每个用户 都使用相同的子目录。这使得只生成一次(例如在构建时生成, 然后随应用程序以只读方式发布)的缓存可以被任何运行 代码的人读取;无法写入该目录的用户仍然可以读取它, 而写入失败只意味着模块会被重新编译。
有两种方式可以启用可移植模式:
-
使用
module.enableCompileCache()中的 portable 选项:// 非可移植缓存(默认):项目移动后缓存会失效 module.enableCompileCache({ directory: '/path/to/cache/storage/dir' }); // 可移植缓存:项目移动后缓存仍然有效 module.enableCompileCache({ directory: '/path/to/cache/storage/dir', portable: true });
提前生成的缓存(例如在构建时生成,以便随应用程序包一起发布)
可以通过 readOnly: true(或 NODE_COMPILE_CACHE_READONLY=1)启用。
然后 Node.js 会加载目录中的任何条目,但从不写入该目录:
没有可用条目的模块会按常规编译但不会被持久化,
module.flushCompileCache() 成为空操作,
并且如果目录不存在也不会创建它。
目前,当将编译缓存与 V8 JavaScript 代码覆盖率 一起使用时,对于从代码缓存反序列化的函数,V8 收集的 覆盖率可能不够精确。建议在运行测试以生成精确覆盖率时 关闭此功能。
一个版本的 Node.js 生成的编译缓存不能被其他版本 的 Node.js 重用。如果使用相同的基础目录持久化缓存, 不同版本生成的缓存将分开存储,因此可以共存。
以下常量作为返回的对象的 status 字段,
该对象由 module.enableCompileCache() 返回,用于指示启用
模块编译缓存 的尝试结果。
| 常量 | 描述 |
|---|---|
ENABLED |
Node.js 已成功启用编译缓存。用于存储编译缓存的
目录将在返回对象的 directory 字段中
返回。
|
ALREADY_ENABLED |
编译缓存此前已启用,可能是通过之前调用
module.enableCompileCache(),或通过设置
NODE_COMPILE_CACHE=dir 环境变量。用于存储编译缓存的
目录将在返回对象的 directory 字段中
返回。
|
FAILED |
Node.js 未能启用编译缓存。这可能是由于缺少
使用指定目录的权限,或各种文件系统错误。
失败的详细信息将在返回对象的 message 字段中
返回。
|
DISABLED |
Node.js 无法启用编译缓存,因为已设置环境变量
NODE_DISABLE_COMPILE_CACHE=1。
|
module.enableCompileCache(options?): voidoptions.directory
。<string>NODE_COMPILE_CACHE=dir
环境变量
指定的目录(如果已设置),否则使用
path.join(os.tmpdir(), 'node-compile-cache')
。<boolean>true
,则启用可移植编译缓存,
即使项目目录被移动也可以重用缓存。这是尽力而为的
功能。如果未指定,则取决于是否设置了环境变量
NODE_COMPILE_CACHE_PORTABLE=1
。<boolean>true
,则使用
directory
中
现有的缓存条目,但从不写入任何内容,并且当目录不存在时
也不会创建它(此时启用会失败)。适用于提前生成并随
应用程序一起发布的缓存。如果未指定,则取决于是否设置了
环境变量
NODE_COMPILE_CACHE_READONLY=1
。<string>
|
<undefined>status
为
module.constants.compileCacheStatus.FAILED
时设置。<string>
|
<undefined>status
为
module.constants.compileCacheStatus.ENABLED
或
module.constants.compileCacheStatus.ALREADY_ENABLED
时设置。在当前 Node.js 实例中启用 模块编译缓存。
对于一般使用场景,建议调用 module.enableCompileCache() 时
不指定 options.directory,以便在需要时可以通过
NODE_COMPILE_CACHE 环境变量覆盖该目录。
由于编译缓存应被视为一种非关键任务的优化,因此在无法启用
编译缓存时,该方法被设计为不抛出任何异常。
相反,它将返回一个对象,其 message 字段包含错误消息,
以帮助调试。如果编译缓存启用成功,返回对象中的
directory 字段包含存储编译缓存的目录路径。
返回对象中的 status 字段将是
module.constants.compileCacheStatus 的某个值,以指示启用 模块编译缓存 的结果。
此方法仅影响当前 Node.js 实例。要在子工作线程中启用它,
可以在子工作线程中也调用此方法,或者将
process.env.NODE_COMPILE_CACHE 设置为编译缓存目录,以便该行为
被继承到子工作线程。目录可以通过此方法返回的 directory 字段
获取,也可以通过 module.getCompileCacheDir() 获取。
module.flushCompileCache(): void将当前 Node.js 实例中已加载模块累积的 模块编译缓存 刷新到磁盘。此方法会在所有刷新 文件系统操作结束后返回,无论其成功与否。 如果出现任何错误,此方法将静默失败,因为编译缓存未命中 不应干扰应用程序的实际运行。
module.getCompileCacheDir(): void- 返回:
<string>|<undefined>如果启用了 模块编译缓存,则返回其目录路径, 否则返回undefined。
Node.js 目前支持两种类型的模块自定义钩子:
module.registerHooks(options):接受同步钩子 函数,这些函数直接在加载模块的线程上运行。module.register(specifier[, parentURL][, options]):接受一个指向 模块的说明符,该模块导出异步钩子函数。这些函数在一个 单独的加载器线程上运行。
异步钩子会因线程间通信而产生额外开销,
并且有 若干注意事项,尤其是在
自定义模块图中的 CommonJS 模块时。
在大多数情况下,为了简单起见,建议通过 module.registerHooks()
使用同步钩子。
稳定性:1.2 - 候选发布
要注册同步自定义钩子,请使用 module.registerHooks(),它
直接接受 同步钩子函数。
// register-hooks.js
import { registerHooks } from 'node:module';
registerHooks({
resolve(specifier, context, nextResolve) { /* implementation */ },
load(url, context, nextLoad) { /* implementation */ },
});可以通过使用 --import 或 --require 标志,在应用代码运行
之前注册钩子。
node --import ./register-hooks.js ./my-app.js
node --require ./register-hooks.js ./my-app.js传给 --import 或 --require 的说明符也可以来自包:
node --import some-package/register ./my-app.js
node --require some-package/register ./my-app.js其中 some-package 有一个 "exports" 字段,将 /register
导出映射到一个调用 registerHooks() 的文件,就像上面的
register-hooks.js 示例一样。
使用 --import 或 --require 可确保在任何应用代码加载之前
注册钩子,包括应用的入口点,并且默认情况下也适用于
任何工作线程。
或者,可以从入口点调用 registerHooks()。
如果入口点需要加载其他模块,并且加载过程需要自定义,
请在注册钩子后使用 require() 或动态 import() 加载它们。
不要在同一个注册钩子的模块中使用静态 import 语句加载
需要自定义的模块,因为静态 import 语句会在导入模块中的
任何代码运行之前(包括对 registerHooks() 的调用)
进行求值,无论静态 import 语句出现在导入模块的
何处。
import { registerHooks } from 'node:module';
registerHooks({ /* implementation of synchronous hooks */ });
// 如果使用静态 import 加载,则加载时不会应用钩子
// my-app.mjs,因为静态导入的模块都会在其导入方之前执行,
// 无论静态导入出现在何处。
// import './my-app.mjs';
// 必须动态加载 my-app.mjs 以确保应用钩子。
await import('./my-app.mjs');或者,可以将内联 JavaScript 代码嵌入 data: URL,以便在应用
代码运行之前注册钩子。例如,
node --import 'data:text/javascript,import {registerHooks} from "node:module"; registerHooks(/* hooks code */);' ./my-app.js钩子是链的一部分,即使该链仅由一个自定义(用户提供的) 钩子和始终存在的默认钩子组成。
钩子函数是嵌套的:每个函数都必须返回一个普通对象,链式调用
是通过每个函数调用 next<hookName>() 实现的,该引用指向
后续加载器的钩子(按 LIFO 顺序)。
可以多次调用 registerHooks():
// entrypoint.mjs
import { registerHooks } from 'node:module';
const hook1 = { /* implementation of hooks */ };
const hook2 = { /* implementation of hooks */ };
// hook2 在 hook1 之前运行。
registerHooks(hook1);
registerHooks(hook2);在此示例中,注册的钩子将形成链。这些链按
后进先出(LIFO)顺序运行。如果 hook1 和 hook2 都定义了 resolve
钩子,则它们的调用顺序如下(注意是从右到左,
从 hook2.resolve 开始,然后是 hook1.resolve,最后是 Node.js 默认钩子):
Node.js 默认 resolve ← hook1.resolve ← hook2.resolve
其他所有钩子也是如此。
如果钩子返回的值缺少必需的属性,则会触发异常。如果钩子
返回时_既_没有调用 next<hookName>() _也_没有返回
shortCircuit: true,也会触发异常。这些错误旨在帮助
防止链中发生意外的中断。在钩子中返回 shortCircuit: true
,以表明链是有意在你的钩子处结束的。
如果希望在加载其他钩子模块时应用某个钩子,则应在该钩子注册 之后再加载其他钩子模块。
registerHooks() 返回的对象有一个 deregister() 方法,可用于
从链中移除钩子。一旦调用 deregister(),这些钩子将不再
在模块解析或加载期间被调用。
目前这仅适用于通过 registerHooks() 注册的同步钩子,
不适用于通过 module.register() 注册的异步钩子。
import { registerHooks } from 'node:module';
const hooks = registerHooks({
resolve(specifier, context, nextResolve) {
console.log('resolve hook called for', specifier);
return nextResolve(specifier, context);
},
load(url, context, nextLoad) {
return nextLoad(url, context);
},
});
// 此时钩子处于活动状态,将针对
// 任何后续的 import() 或 require() 调用被调用。
await import('./my-module.mjs');
// 稍后,从链中移除钩子。
hooks.deregister();
// 后续加载将不再触发钩子。
await import('./another-module.mjs');module.registerHooks() 接受的钩子函数
History
module.registerHooks() 方法接受以下同步钩子函数。
function resolve(specifier, context, nextResolve) {
// 接受 `import` 或 `require` 说明符并将其解析为 URL。
}
function load(url, context, nextLoad) {
// 接受已解析的 URL 并返回要计算的源代码。
}同步钩子在与模块加载相同的线程和相同的 realm 中运行, 因此钩子函数中的代码可以通过全局变量或其他共享状态 直接向被引用的模块传递值。
与异步钩子不同,同步钩子默认情况下不会继承到子工作线程,
不过如果钩子是使用 --import 或 --require 预加载的文件注册的,
子工作线程可以通过 process.execArgv 继承预加载的脚本。
详见 Worker 的文档。
<string><Object><string>package.json
的导出条件<Object><string>
|
<undefined><Function>resolve
钩子,
或者是最后一个用户提供的
resolve
钩子之后的 Node.js 默认
resolve
钩子<string><Object>
|
<undefined><string>
|
<null>
|
<undefined>load
钩子的提示(可能会被忽略)。
它可以是模块格式(如
'commonjs'
或
'module'
),也可以是任意值,
如
'css'
或
'yaml'
。<Object>
|
<undefined><undefined>
|
<boolean>resolve
钩子链的信号。
默认值:
false<string>resolve 钩子链负责告诉 Node.js 在何处查找以及如何
缓存给定的 import 语句、表达式或 require 调用。它可以
选择性地返回一个格式(如 'module')作为给 load 钩子的提示。
如果指定了格式,load 钩子最终负责提供最终的 format 值
(它可以自由忽略 resolve 提供的提示);如果 resolve 提供了 format,
则需要自定义 load 钩子,即使只是为了将该值传递给
Node.js 默认的 load 钩子。
导入类型属性是将已加载模块保存到内部模块缓存时
缓存键的一部分。如果模块应使用与源代码中
不同的属性进行缓存,则 resolve 钩子负责返回
importAttributes 对象。
context 中的 conditions 属性是一个条件数组,
将用于匹配此解析请求的 包导出条件。
它们可用于在其他地方查找条件映射,或在调用默认解析逻辑时
修改该列表。
当前的 包导出条件 总是包含在
传入钩子的 context.conditions 数组中。为了保证调用 defaultResolve 时
默认的 Node.js 模块说明符解析行为,传给它的 context.conditions
数组_必须_包含最初传入 resolve 钩子的 context.conditions
数组的_所有_元素。
import { registerHooks } from 'node:module';
function resolve(specifier, context, nextResolve) {
// 调用 `defaultResolve` 时,可以修改参数。例如,
// 修改说明符或添加适用的导出条件。
if (specifier.includes('foo')) {
specifier = specifier.replace('foo', 'bar');
return nextResolve(specifier, {
...context,
conditions: [...context.conditions, 'another-condition'],
});
}
// 钩子也可以跳过默认解析并提供自定义 URL。
if (specifier === 'special-module') {
return {
url: 'file:///path/to/special-module.mjs',
format: 'module',
shortCircuit: true, // This is mandatory if nextResolve() is not called.
};
}
// 如果不需要自定义,则交由链中的下一个钩子处理,
// 如果这是最后一个用户指定的加载器,则为 Node.js 默认解析。
return nextResolve(specifier);
}
registerHooks({ resolve });<string>resolve
链返回的 URL<Object><string>package.json
的导出条件<string>
|
<null>
|
<undefined>resolve
钩子链选择性提供的
格式。作为输入,它可以是任何字符串值;输入值不需要
符合下面描述的可接受返回值列表。<Object><Function>load
钩子,或者
在最后一个用户提供的
load
钩子之后的 Node.js 默认
load
钩子<string><Object>
|
<undefined>nextLoad
中,如果
url
指向的模块没有明确的模块类型信息,则
context.format
是必需的。<undefined>
|
<boolean>load
钩子链的信号。
默认值:
false<string>
|
<ArrayBuffer>
|
<TypedArray>load 钩子提供了一种定义自定义方法来获取
已解析 URL 源代码的方式。这可能使加载器能够避免
从磁盘读取文件。它还可用于将无法识别的格式映射为
受支持的格式,例如将 yaml 映射为 module。
import { registerHooks } from 'node:module';
import { Buffer } from 'node:buffer';
function load(url, context, nextLoad) {
// 钩子可以跳过默认加载并提供自定义源代码。
if (url === 'special-module') {
return {
source: 'export const special = 42;',
format: 'module',
shortCircuit: true, // This is mandatory if nextLoad() is not called.
};
}
// 可以修改下一步(可能是默认步骤)加载的源代码,
// 例如,在模块的源代码中将 'foo' 替换为 'bar'。
const result = nextLoad(url, context);
const source = typeof result.source === 'string' ?
result.source : Buffer.from(result.source).toString('utf8');
return {
source: source.replace(/foo/g, 'bar'),
...result,
};
}
registerHooks({ load });在更高级的场景中,这也可用于将不支持的源代码 转换为支持的源代码(请参阅下面的 示例)。
format 的最终值必须是以下之一:
format | 描述 | load 返回的 source 的可接受类型 |
|---|---|---|
'addon' | 加载 Node.js 插件 | <null> |
'builtin' | 加载 Node.js 内置模块 | <null> |
'commonjs-typescript' | 加载使用 TypeScript 语法的 Node.js CommonJS 模块 | <string> | <ArrayBuffer> | <TypedArray> | <null> | <undefined> |
'commonjs' | 加载 Node.js CommonJS 模块 | <string> | <ArrayBuffer> | <TypedArray> | <null> | <undefined> |
'json' | 加载 JSON 文件 | <string> | <ArrayBuffer> | <TypedArray> |
'module-typescript' | 加载使用 TypeScript 语法的 ES 模块 | <string> | <ArrayBuffer> | <TypedArray> |
'module' | 加载 ES 模块 | <string> | <ArrayBuffer> | <TypedArray> |
'wasm' | 加载 WebAssembly 模块 | <ArrayBuffer> | <TypedArray> |
对于格式 'builtin',source 的值会被忽略,因为目前
无法替换 Node.js 内置(核心)模块的值。
这些类型都对应于 ECMAScript 中定义的类。
- 具体的
<ArrayBuffer>对象是<SharedArrayBuffer>。 - 具体的
<TypedArray>对象是<Uint8Array>。
如果文本类格式(即 'json'、'module')的 source 值
不是字符串,则会使用 util.TextDecoder 将其转换为字符串。
稳定性:1.1 - 活跃开发中
异步自定义钩子有诸多注意事项,且尚不确定其
问题能否得到解决。建议用户改用同步自定义钩子,
即通过 module.registerHooks() 来避开这些注意事项。
- 异步钩子在单独的线程中运行,因此钩子函数无法直接 修改被自定义模块的全局状态。通常使用消息 通道和原子操作在两者之间传递数据,或影响控制流。 请参阅与异步模块自定义钩子的通信。
- 异步钩子不会影响模块图中所有的
require()调用。- 使用
module.createRequire()创建的自定义require函数不受 影响。 - 如果异步
load钩子没有为经过它的 CommonJS 模块覆盖source, 那么这些 CommonJS 模块通过内置require()加载的子模块 也不会受到异步钩子的影响。
- 使用
- 在自定义 CommonJS 模块时,异步钩子需要处理若干注意事项。
详情请参阅 异步
resolve钩子 和 异步load钩子。 - 当 CommonJS 模块内部的
require()调用被异步钩子自定义时, Node.js 可能需要多次加载该 CommonJS 模块的源代码,以保持 与现有 CommonJS 猴子补丁的兼容性。如果模块代码在两次加载之间 发生变化,可能会导致意外行为。- 作为副作用,如果同时注册了异步钩子和同步钩子,且
异步钩子选择自定义该 CommonJS 模块,那么同步钩子可能会
针对该 CommonJS 模块中的
require()调用被多次调用。
- 作为副作用,如果同时注册了异步钩子和同步钩子,且
异步钩子选择自定义该 CommonJS 模块,那么同步钩子可能会
针对该 CommonJS 模块中的
异步自定义钩子使用 module.register() 注册,该方法接受
一个指向另一模块(该模块导出异步钩子函数)的路径或 URL。
与 registerHooks() 类似,register() 可以在由 --import 或
--require 预加载的模块中调用,也可以直接在入口点中调用。
// 使用 module.register() 在专用线程中注册异步钩子。
import { register } from 'node:module';
register('./hooks.mjs', import.meta.url);
// 如果 my-app.mjs 在此处通过 `import './my-app.mjs'` 静态加载,由于 ESM
// 依赖项会在导入它们的模块之前被求值,
// 它会在上述钩子注册 _之前_ 被加载,因此不会受到影响。
// 为确保钩子生效,必须使用动态 import() 来加载 ESM
// (在钩子注册之后)。
import('./my-app.mjs');在 hooks.mjs 中:
// hooks.mjs
export async function resolve(specifier, context, nextResolve) {
/* 具体实现 */
}
export async function load(url, context, nextLoad) {
/* 具体实现 */
}与同步钩子不同,异步钩子不会作用于调用 register() 的文件
中所加载的这些模块:
// register-hooks.js
import { register, createRequire } from 'node:module';
register('./hooks.mjs', import.meta.url);
// 异步钩子不会影响通过自定义 require()
// 函数(由 module.createRequire() 创建)加载的模块。
const userRequire = createRequire(import.meta.filename);
userRequire('./my-app-2.cjs'); // Hooks won't affect this异步钩子也可以通过 --import 标志使用 data: URL 来注册:
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("my-instrumentation", pathToFileURL("./"));' ./my-app.jsregister() 的链接方式与 registerHooks() 类似。如果混合使用同步和异步
钩子,那么同步钩子总是先运行,之后异步
钩子才开始运行。也就是说,在最后一个运行的同步钩子中,其 next
钩子包含了对异步钩子的调用。
// entrypoint.mjs
import { register } from 'node:module';
register('./foo.mjs', import.meta.url);
register('./bar.mjs', import.meta.url);
await import('./my-app.mjs');如果 foo.mjs 和 bar.mjs 定义了 resolve 钩子,它们的调用顺序如下
(注意是从右到左,先 ./bar.mjs,再 ./foo.mjs,最后是 Node.js 默认):
Node.js 默认 ← ./foo.mjs ← ./bar.mjs
使用异步钩子时,已注册的钩子也会影响后续的
register 调用,这些调用负责加载钩子模块。在上面的示例中,
bar.mjs 将经由 foo.mjs 注册的钩子进行解析和加载
(因为 foo 的钩子已经被加入链中)。这允许
诸如用非 JavaScript 语言编写钩子之类的做法,只要
更早注册的钩子能将其转译为 JavaScript。
不能从运行钩子模块的线程中调用 register() 方法,该线程
运行导出异步钩子的模块或其依赖项。
异步钩子在专用线程中运行,与运行应用程序代码的 主线程相分离。这意味着修改全局变量不会 影响其他线程,必须使用消息通道在线程之间 进行通信。
register 方法可用于向 initialize 钩子传递数据。
传递给钩子的数据可以包含端口等可转移对象。
import { register } from 'node:module';
import { MessageChannel } from 'node:worker_threads';
// 此示例演示如何使用消息通道
// 通过将 `port2` 发送给钩子来与钩子通信。
const { port1, port2 } = new MessageChannel();
port1.on('message', (msg) => {
console.log(msg);
});
port1.unref();
register('./my-hooks.mjs', {
parentURL: import.meta.url,
data: { number: 1, port: port2 },
transferList: [port2],
});register 方法可用于注册一个模块,该模块导出一组
钩子。这些钩子是由 Node.js 调用的函数,用于自定义
模块解析和加载过程。导出的函数必须具有特定的
名称和签名,并且必须作为命名导出导出。
export async function initialize({ number, port }) {
// 接收来自 `register` 的数据。
}
export async function resolve(specifier, context, nextResolve) {
// 接受一个 `import` 或 `require` 说明符,并将其解析为 URL。
}
export async function load(url, context, nextLoad) {
// 接受一个已解析的 URL,并返回待求值的源代码。
}异步钩子在单独的线程中运行,与运行应用程序代码的
主线程相隔离。这意味着它处于不同的域中。钩子线程
可能随时被主线程终止,因此不要依赖
异步操作(如 console.log)的完成。默认情况下,它们会被继承到
子工作线程中。
initialize(): void<any>register(loader, import.meta.url, { data })
的数据。initialize 钩子仅被 register 接受。registerHooks() 既不支持
也不需要它,因为同步钩子的初始化可以直接在调用
registerHooks() 之前运行。
initialize 钩子提供了一种方式,用于定义在钩子模块初始化时
在钩子线程中运行的自定义函数。初始化发生在
通过 register 注册钩子模块时。
该钩子可以接收来自 register 调用的数据,包括
端口和其他可转移对象。initialize 的返回值可以是
<Promise>,在这种情况下,主线程会在继续
执行之前等待它。
模块自定义代码:
// path-to-my-hooks.js
export async function initialize({ number, port }) {
port.postMessage(`increment: ${number + 1}`);
}调用方代码:
import assert from 'node:assert';
import { register } from 'node:module';
import { MessageChannel } from 'node:worker_threads';
// 此示例展示如何使用消息通道
// 在主(应用程序)线程与运行于钩子
// 线程上的钩子之间进行通信,方式是将 `port2` 发送给 `initialize` 钩子。
const { port1, port2 } = new MessageChannel();
port1.on('message', (msg) => {
assert.strictEqual(msg, 'increment: 2');
});
port1.unref();
register('./path-to-my-hooks.js', {
parentURL: import.meta.url,
data: { number: 1, port: port2 },
transferList: [port2],
});<string><Object><string>package.json
的导出条件<Object><string>
|
<undefined><Function>resolve
钩子,或
最后一个用户提供的
resolve
钩子之后的 Node.js 默认
resolve
钩子<string><Object>
|
<undefined><string>
|
<null>
|
<undefined>load
钩子的提示(可能会被忽略)。它可以是
模块格式(如
'commonjs'
或
'module'
),也可以是
'css'
或
'yaml'
之类的任意值。<Object>
|
<undefined><undefined>
|
<boolean>resolve
钩子链的信号。
默认值:
false<string>异步版本的工作方式与同步版本类似,区别在于
nextResolve 函数返回一个 Promise,且 resolve 钩子本身也可以返回一个 Promise。
警告 在异步版本中,尽管支持返回 Promise 和异步函数,但对
resolve的调用仍可能阻塞主线程,从而 影响性能。
警告 对于由异步钩子自定义的 CommonJS 模块,其内部
require()调用所触发的resolve钩子不会收到传递给require()的原始说明符。相反,它收到的是使用默认 CommonJS 解析方式 已完全解析的 URL。
警告 在由异步自定义钩子自定义的 CommonJS 模块中,
require.resolve()和require()将使用"import"导出条件,而非"require",这在加载双模式包时可能会导致意外行为。
export async function resolve(specifier, context, nextResolve) {
// 调用 `defaultResolve` 时,可以修改参数。例如,
// 更改说明符或添加条件。
if (specifier.includes('foo')) {
specifier = specifier.replace('foo', 'bar');
return nextResolve(specifier, {
...context,
conditions: [...context.conditions, 'another-condition'],
});
}
// 该钩子也可以跳过默认解析,并提供自定义 URL。
if (specifier === 'special-module') {
return {
url: 'file:///path/to/special-module.mjs',
format: 'module',
shortCircuit: true, // This is mandatory if not calling nextResolve().
};
}
// 如果不需要自定义,则转交给链中的下一个钩子,如果这是最后一个用户指定的
// 加载器,那么下一个钩子就是 Node.js 默认的解析钩子。
return nextResolve(specifier);
}<string>resolve
链返回的 URL<Object><string>package.json
的导出条件<string>
|
<null>
|
<undefined>resolve
钩子链可选提供的
格式。作为输入,它可以是任意字符串值;输入值无需
符合下文所述的可接受返回值列表。<Object><Function>load
钩子,或
最后一个用户提供的
load
钩子之后的 Node.js 默认
load
钩子<string><Object>
|
<undefined>nextLoad
中,如果
url
所指向的模块没有明确的模块类型信息,
则
context.format
是必需的。<string><undefined>
|
<boolean>load
钩子链的信号。
默认值:
false<string>
|
<ArrayBuffer>
|
<TypedArray>警告:异步
load钩子与 CommonJS 模块的命名空间导出 不兼容。同时使用它们将导致导入得到 一个空对象。未来可能会解决此问题。这不适用于 同步load钩子,在这种情况下导出可以照常使用。
异步版本的工作方式与同步版本类似,不过在使用异步 load 钩子时,
为 'commonjs' 省略 source 与提供 source
的效果截然不同:
- 当提供
source时,该模块中的所有require调用将 由 ESM 加载器使用已注册的resolve和load钩子处理;该模块 中的所有require.resolve调用将由 ESM 加载器 使用已注册的resolve钩子处理;只有一部分 CommonJS API 可用(例如没有require.extensions、没有require.cache、没有require.resolve.paths),并且对 CommonJS 模块加载器的猴子补丁 将不会生效。 - 如果
source为 undefined 或null,它将由 CommonJS 模块 加载器处理,且require/require.resolve调用不会经过 已注册的钩子。这种对空值source的行为是临时的——未来 将不再支持空值source。
这些注意事项不适用于同步 load 钩子,在这种情况下,
被自定义的 CommonJS 模块可以使用完整的 CommonJS API,
且 require/require.resolve 始终经过已注册的
钩子。
Node.js 内部的异步 load 实现(即 load 链中最后一个钩子的 next 值),
当 format 为 'commonjs' 时,出于向后兼容会为 source 返回 null。
以下是一个示例钩子,它选择
使用非默认行为:
import { readFile } from 'node:fs/promises';
// 异步版本(由 module.register() 接受)不需要此修复;
// 同步版本(由 module.registerHooks() 接受)也不需要。
export async function load(url, context, nextLoad) {
const result = await nextLoad(url, context);
if (result.format === 'commonjs') {
result.source ??= await readFile(new URL(result.responseURL ?? url));
}
return result;
}这也不适用于同步 load 钩子,在这种情况下,返回的
source 包含由下一个钩子加载的源代码,无论
模块格式如何。
各种模块自定义钩子可以一起使用,以实现 对 Node.js 代码加载和求值行为的 广泛自定义。
下面的钩子注册了一些钩子,以对此类说明符提供基本的 支持。虽然这看起来像是 Node.js 核心 功能的一大改进,但实际使用这些钩子有诸多弊端: 性能比从磁盘加载文件慢得多,没有缓存, 也没有安全性。
// https-hooks.mjs
import { get } from 'node:https';
export function load(url, context, nextLoad) {
// 要通过加载网络上的 JavaScript,我们需要获取并
// 返回它。
if (url.startsWith('https://')) {
return new Promise((resolve, reject) => {
get(url, (res) => {
let data = '';
res.setEncoding('utf8');
res.on('data', (chunk) => data += chunk);
res.on('end', () => resolve({
// 此示例假定所有网络提供的 JavaScript 都是 ES 模块
// 代码。
format: 'module',
shortCircuit: true,
source: data,
}));
}).on('error', (err) => reject(err));
});
}
// 让 Node.js 处理所有其他 URL。
return nextLoad(url);
}使用上述钩子模块,运行
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs
会根据 main.mjs 中 URL 处的模块打印 CoffeeScript 的
当前版本。
Node.js 无法理解的格式的源代码可以使用
load 钩子转换为 JavaScript。
这比在运行 Node.js 之前转译源文件的性能要低; 转译器钩子应仅用于开发和测试目的。
// coffeescript-hooks.mjs
import { readFile } from 'node:fs/promises';
import { findPackageJSON } from 'node:module';
import coffeescript from 'coffeescript';
const extensionsRegex = /\.(coffee|litcoffee|coffee\.md)$/;
export async function load(url, context, nextLoad) {
if (extensionsRegex.test(url)) {
// CoffeeScript 文件可以是 CommonJS 模块,也可以是 ES 模块。使用自定义格式
// 告诉 Node.js 不要检测其模块类型。
const { source: rawSource } = await nextLoad(url, { ...context, format: 'coffee' });
// 此钩子会将 CoffeeScript 源代码
// 转换为 JavaScript 源代码,适用于所有导入的 CoffeeScript 文件。
const transformedSource = coffeescript.compile(rawSource.toString(), url);
// 要确定 Node.js 如何解释转译结果,
// 请沿文件系统向上搜索最近的父级 package.json 文件,
// 并读取其 "type" 字段。
return {
format: await getPackageType(url),
shortCircuit: true,
source: transformedSource,
};
}
// 让 Node.js 处理所有其他 URL。
return nextLoad(url, context);
}
async function getPackageType(url) {
// `url` 仅在第一次迭代(即从 load() 钩子接收
// 已解析的 url 时)才是文件路径
// 来自 load() 的实际文件路径会包含文件扩展名,因为
// 规范对此有要求
// 这种对 `url` 是否包含扩展名的简单真值检查
// 适用于大多数项目,但无法覆盖某些边缘情况(例如
// 无扩展名的文件或以空格结尾的 URL)。
const pJson = findPackageJSON(url);
return readFile(pJson, 'utf8')
.then(JSON.parse)
.then((json) => json?.type)
.catch(() => undefined);
}// coffeescript-sync-hooks.mjs
import { readFileSync } from 'node:fs';
import { registerHooks, findPackageJSON } from 'node:module';
import coffeescript from 'coffeescript';
const extensionsRegex = /\.(coffee|litcoffee|coffee\.md)$/;
function load(url, context, nextLoad) {
if (extensionsRegex.test(url)) {
const { source: rawSource } = nextLoad(url, { ...context, format: 'coffee' });
const transformedSource = coffeescript.compile(rawSource.toString(), url);
return {
format: getPackageType(url),
shortCircuit: true,
source: transformedSource,
};
}
return nextLoad(url, context);
}
function getPackageType(url) {
const pJson = findPackageJSON(url);
if (!pJson) {
return undefined;
}
try {
const file = readFileSync(pJson, 'utf-8');
return JSON.parse(file)?.type;
} catch {
return undefined;
}
}
registerHooks({ load });# main.coffee
import { scream } from './scream.coffee'
console.log scream 'hello, world'
import { version } from 'node:process'
console.log "Brought to you by Node.js version #{version}"为运行该示例,请添加一个 package.json 文件,其中包含
CoffeeScript 文件的模块类型。
{
"type": "module"
}这仅用于运行示例。在实际应用中,加载器中的 getPackageType() 必须
能够返回 Node.js 已知的 format,即使 package.json 中没有
显式指定类型,否则 nextLoad 调用会抛出 ERR_UNKNOWN_FILE_EXTENSION
(若为 undefined)或 ERR_UNKNOWN_MODULE_FORMAT(若它不是已知的
加载钩子 文档中列出的格式)。
使用上述钩子模块,运行
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee
或 node --import ./coffeescript-sync-hooks.mjs ./main.coffee
会使 main.coffee 在其源代码从磁盘加载之后、Node.js 执行之前
被转换为 JavaScript;任何被加载文件中通过 import 语句引用的
.coffee、.litcoffee 或 .coffee.md 文件,
也是如此。
前面两个示例定义了 load 钩子。这是一个 resolve 钩子的示例。
该钩子模块读取一个 import-map.json 文件,该文件定义了
要将哪些说明符覆盖为其他 URL(这是 "导入映射" 规范中
一小部分功能的非常简单的实现)。
// import-map-hooks.js
import fs from 'node:fs/promises';
const { imports } = JSON.parse(await fs.readFile('import-map.json'));
export async function resolve(specifier, context, nextResolve) {
if (Object.hasOwn(imports, specifier)) {
return nextResolve(imports[specifier], context);
}
return nextResolve(specifier, context);
}// import-map-sync-hooks.js
import fs from 'node:fs/promises';
import module from 'node:module';
const { imports } = JSON.parse(fs.readFileSync('import-map.json', 'utf-8'));
function resolve(specifier, context, nextResolve) {
if (Object.hasOwn(imports, specifier)) {
return nextResolve(imports[specifier], context);
}
return nextResolve(specifier, context);
}
module.registerHooks({ resolve });使用以下文件:
// main.js
import 'a-module';运行 node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js
或 node --import ./import-map-sync-hooks.js main.js
应打印 some module!。
Source Map 支持
History
稳定性:1 - 实验性
Node.js 支持 TC39 ECMA-426 Source Map 格式(它曾被称为 Source map 修订版 3 格式)。
本节中的 API 是用于与源映射缓存交互的辅助工具。 当启用源映射解析且在模块尾部找到 源映射包含指令 时,会填充此缓存。
要启用源映射解析,必须使用标志
--enable-source-maps 运行 Node.js,或通过设置
NODE_V8_COVERAGE=dir 启用代码覆盖率,或通过
module.setSourceMapsSupport() 以编程方式启用。
// module.mjs
// 在 ECMAScript 模块中
import { findSourceMap, SourceMap } from 'node:module';module.getSourceMapsSupport(): void- 返回:
<Object>Attributes
此方法返回是否为堆栈跟踪启用了 Source Map v3 支持。
module.findSourceMap(path): void<string>path 是需要获取相应源映射的文件的
解析后路径。
module.setSourceMapsSupport(enabled, options?): void此函数启用或禁用对堆栈跟踪的 Source Map v3 支持。
它提供与使用命令行选项
--enable-source-maps 启动 Node.js 进程相同的功能,并提供了额外的选项来更改对
node_modules 中的文件或生成代码的支持。
只有在启用源映射之后加载的 JavaScript 文件中的源映射
才会被解析和加载。最好使用命令行选项 --enable-source-maps,
以避免丢失在此 API 调用之前加载的模块的
源映射。
类:module.SourceMap
History
new SourceMap(payload, { lineLengths }?): void创建一个新的 sourceMap 实例。
payload 是一个对象,其键与源映射格式相匹配:
lineLengths 是一个可选数组,包含生成代码中
每一行的长度。
- 返回:
<Object>
用于构造 SourceMap 实例的 payload 的 getter。
sourceMap.findEntry(lineOffset, columnOffset): void给定生成源文件中的行偏移量和列偏移量, 如果找到,则返回一个对象,表示 SourceMap 在 原始文件中的范围,否则返回空对象。
返回的对象包含以下键:
返回值表示 SourceMap 中呈现的原始范围, 它基于从零开始的偏移量,而非 Error 消息和 CallSite 对象中出现的从 1 开始的行号和 列号。
要从 Error 堆栈和 CallSite 对象报告的
lineNumber 和 columnNumber 中获取对应的从 1 开始的
行号和列号,请使用 sourceMap.findOrigin(lineNumber,
columnNumber)`。
sourceMap.findOrigin(lineNumber, columnNumber): void给定生成源代码中某个调用点的从 1 开始的
lineNumber 和 columnNumber,在原始源代码中查找
对应的调用点位置。
如果提供的 lineNumber 和 columnNumber 在任何源映射中都
未找到,则返回空对象。否则,返回的
对象包含以下键:
<string>
|
<undefined><string><number><number>