initialize()


稳定性: 1.2 - 发布候选版

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

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 transferrable 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],
});