异步自定义钩子的注册
🌐 Registration of asynchronous customization hooks
异步自定义钩子使用 module.register() 注册,该 module.register() 接受指向导出 异步钩子函数 的另一个模块的路径或 URL。
🌐 Asynchronous customization hooks are registered using module.register() which takes
a path or URL to another module that exports the asynchronous hook functions.
类似于 registerHooks(),register() 可以在 --import 或 --require 预加载的模块中被调用,或者直接在入口点内被调用。
🌐 Similar to registerHooks(), register() can be called in a module preloaded by --import or
--require, or called directly within the entry point.
// Use module.register() to register asynchronous hooks in a dedicated thread.
import { register } from 'node:module';
register('./hooks.mjs', import.meta.url);
// If my-app.mjs is loaded statically here as `import './my-app.mjs'`, since ESM
// dependencies are evaluated before the module that imports them,
// it's loaded _before_ the hooks are registered above and won't be affected.
// To ensure the hooks are applied, dynamic import() must be used to load ESM
// after the hooks are registered.
import('./my-app.mjs');const { register } = require('node:module');
const { pathToFileURL } = require('node:url');
// Use module.register() to register asynchronous hooks in a dedicated thread.
register('./hooks.mjs', pathToFileURL(__filename));
import('./my-app.mjs');在 hooks.mjs 中:
🌐 In hooks.mjs:
// hooks.mjs
export async function resolve(specifier, context, nextResolve) {
/* implementation */
}
export async function load(url, context, nextLoad) {
/* implementation */
} 与同步钩子不同,对于在调用 register() 的文件中加载的这些模块,异步钩子不会运行:
🌐 Unlike synchronous hooks, the asynchronous hooks would not run for these modules loaded in the file
that calls register():
// register-hooks.js
import { register, createRequire } from 'node:module';
register('./hooks.mjs', import.meta.url);
// Asynchronous hooks does not affect modules loaded via custom require()
// functions created by module.createRequire().
const userRequire = createRequire(__filename);
userRequire('./my-app-2.cjs'); // Hooks won't affect this // register-hooks.js
const { register, createRequire } = require('node:module');
const { pathToFileURL } = require('node:url');
register('./hooks.mjs', pathToFileURL(__filename));
// Asynchronous hooks does not affect modules loaded via built-in require()
// in the module calling `register()`
require('./my-app-2.cjs'); // Hooks won't affect this
// .. or custom require() functions created by module.createRequire().
const userRequire = createRequire(__filename);
userRequire('./my-app-3.cjs'); // Hooks won't affect this 异步钩子也可以使用带有 --import 标志的 data: URL 来注册:
🌐 Asynchronous hooks can also be registered using a data: URL with the --import flag:
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("my-instrumentation", pathToFileURL("./"));' ./my-app.js