钩子


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

钩子是链的一部分,即使该链仅由一个自定义(用户提供的)钩子和始终存在的默认钩子组成。钩子函数嵌套:每个都必须始终返回一个普通对象,并且链接是由于每个函数调用 next<hookName>() 而发生的,next<hookName>() 是对后续加载程序钩子的引用。

¥Hooks are part of a chain, even if that chain consists of only one custom (user-provided) hook and the default hook, which is always present. Hook functions nest: each one must always return a plain object, and chaining happens as a result of each function calling next<hookName>(), which is a reference to the subsequent loader's hook.

返回缺少必需属性的值的钩子会触发异常。没有调用 next<hookName>() 和没有返回 shortCircuit: true 就返回的钩子也会触发异常。这些错误有助于防止链中的意外中断。从钩子返回 shortCircuit: true 表示该链有意在你的钩子处结束。

¥A hook that returns a value lacking a required property triggers an exception. A hook that returns without calling next<hookName>() and without returning shortCircuit: true also triggers an exception. These errors are to help prevent unintentional breaks in the chain. Return shortCircuit: true from a hook to signal that the chain is intentionally ending at your hook.

钩子在单独的线程中运行,与运行应用代码的主线程隔离。这意味着它是一个不同的 realm。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.

Node.js 中文网 - 粤ICP备13048890号