initialize()


稳定性: 1.2 - 发布候选版

  • data <any> 来自 register(loader, import.meta.url, { data }) 的数据。

initialize 钩子仅被 register 接受。registerHooks() 不支持也不需要它,因为同步钩子的初始化可以在调用 registerHooks() 之前直接执行。

【The initialize hook is only accepted by register. registerHooks() does not support nor need it since initialization done for synchronous hooks can be run directly before the call to registerHooks().】

initialize 钩子提供了一种方式,可以定义一个自定义函数,当 hooks 模块初始化时,该函数将在 hooks 线程中运行。当通过 register 注册 hooks 模块时,初始化就会发生。

【The initialize hook provides a way to define a custom function that runs in the hooks thread when the hooks module is initialized. Initialization happens when the hooks module is registered via register.】

这个钩子可以从 register 调用接收数据,包括端口和其他可传递对象。initialize 的返回值可以是一个 <Promise>,在这种情况下,它将在主应用线程执行恢复之前被等待。

【This hook can receive data from a register invocation, including ports and other transferable objects. The return value of initialize can be a <Promise>, in which case it will be awaited before the main application thread execution resumes.】

模块定制代码:

【Module customization code:】

// path-to-my-hooks.js

export async function initialize({ number, port }) {
  port.postMessage(`increment: ${number + 1}`);
} 

调用者代码:

【Caller code:】

import assert from 'node:assert';
import { register } from 'node:module';
import { MessageChannel } from 'node:worker_threads';

// This example showcases how a message channel can be used to communicate
// between the main (application) thread and the hooks running on the hooks
// thread, by sending `port2` to the `initialize` hook.
const { port1, port2 } = new MessageChannel();

port1.on('message', (msg) => {
  assert.strictEqual(msg, 'increment: 2');
});
port1.unref();

register('./path-to-my-hooks.js', {
  parentURL: import.meta.url,
  data: { number: 1, port: port2 },
  transferList: [port2],
});const assert = require('node:assert');
const { register } = require('node:module');
const { pathToFileURL } = require('node:url');
const { MessageChannel } = require('node:worker_threads');

// This example showcases how a message channel can be used to communicate
// between the main (application) thread and the hooks running on the hooks
// thread, by sending `port2` to the `initialize` hook.
const { port1, port2 } = new MessageChannel();

port1.on('message', (msg) => {
  assert.strictEqual(msg, 'increment: 2');
});
port1.unref();

register('./path-to-my-hooks.js', {
  parentURL: pathToFileURL(__filename),
  data: { number: 1, port: port2 },
  transferList: [port2],
});