钩子


【Hooks】

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

Hooks 是 链条 的一部分,即使该链只包含一个自定义(用户提供的)hook 和始终存在的默认 hook。Hook 函数是嵌套的:每个函数必须总是返回一个普通对象,而链式调用的发生是因为每个函数调用了 next<hookName>(),它是对后续加载器的 hook 的引用(按后进先出顺序)。

返回缺少必需属性的值的钩子会触发异常。一个钩子如果没有调用 next<hookName>() 并且也没有返回 shortCircuit: true,同样会触发异常。这些错误是为了帮助防止链条意外中断。从钩子返回 shortCircuit: true 表示链条在你的钩子处故意结束。

Hooks 在单独的线程中运行,与运行应用代码的主线程隔离。这意味着它是一个不同的 字段。主线程可以在任何时候终止 hooks 线程,所以不要依赖异步操作(如 console.log)来完成。

【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.】