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.
} 

异步钩子在一个独立的线程中运行,与执行应用代码的主线程隔离。这意味着它是一个不同的字段。钩子线程可能会随时被主线程终止,因此不要依赖异步操作(如 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.】