module.register() 接受的异步钩子


¥Asynchronous hooks accepted by module.register()

register 方法可用于注册导出一组钩子的模块。钩子是 Node.js 调用的函数,用于自定义模块解析和加载过程。导出的函数必须具有特定的名称和签名,并且必须作为命名导出导出。

¥The register method can be used to register a module that exports a set of hooks. The hooks are functions that are called by Node.js to customize the module resolution and loading process. The exported functions must have specific names and signatures, and they must be exported as named exports.

export async function initialize({ number, port }) {
  // Receives data from `register`.
}

export async function resolve(specifier, context, nextResolve) {
  // Take an `import` or `require` specifier and resolve it to a URL.
}

export async function load(url, context, nextLoad) {
  // Take a resolved URL and return the source code to be evaluated.
} 

异步钩子在单独的线程中运行,与运行应用代码的主线程隔离。这意味着它是一个不同的 realm。hooks 线程随时可能被主线程终止,所以不要依赖异步操作(如 console.log)来完成。默认情况下,它们被继承到子工作程序中。

¥Asynchronous hooks are run in a separate thread, isolated from the main thread where application code runs. That means it is a different realm. The hooks thread may be terminated by the main thread at any time, so do not depend on asynchronous operations (like console.log) to complete. They are inherited into child workers by default.