链接
【Chaining】
可以多次调用 register:
【It's possible to call register more than once:】
// entrypoint.mjs
import { register } from 'node:module';
register('./foo.mjs', import.meta.url);
register('./bar.mjs', import.meta.url);
await import('./my-app.mjs');// entrypoint.cjs
const { register } = require('node:module');
const { pathToFileURL } = require('node:url');
const parentURL = pathToFileURL(__filename);
register('./foo.mjs', parentURL);
register('./bar.mjs', parentURL);
import('./my-app.mjs');在这个例子中,注册的钩子将形成链。这些链以后进先出(LIFO)的顺序运行。如果 foo.mjs 和 bar.mjs 都定义了 resolve 钩子,它们将按如下方式调用(注意从右到左):
node 默认 ← ./foo.mjs ← ./bar.mjs
(从 ./bar.mjs 开始,然后是 ./foo.mjs,最后是 Node.js 默认)。
其他所有钩子也同样适用。
【In this example, the registered hooks will form chains. These chains run
last-in, first out (LIFO). If both foo.mjs and bar.mjs define a resolve
hook, they will be called like so (note the right-to-left):
node's default ← ./foo.mjs ← ./bar.mjs
(starting with ./bar.mjs, then ./foo.mjs, then the Node.js default).
The same applies to all the other hooks.】
已注册的钩子也会影响 register 本身。在这个例子中,bar.mjs 将通过 foo.mjs 注册的钩子来解析和加载(因为 foo 的钩子已经被添加到链中)。这允许像使用非 JavaScript 语言编写钩子这样的操作,只要先前注册的钩子能够转译成 JavaScript。
【The registered hooks also affect register itself. In this example,
bar.mjs will be resolved and loaded via the hooks registered by foo.mjs
(because foo's hooks will have already been added to the chain). This allows
for things like writing hooks in non-JavaScript languages, so long as
earlier registered hooks transpile into JavaScript.】
register 方法不能在定义钩子的模块内部调用。
【The register method cannot be called from within the module that defines the
hooks.】