initialize()
¥Stability: 1.1 - Active development
-
data
<any> 数据来自register(loader, import.meta.url, { data })
。¥
data
<any> The data fromregister(loader, import.meta.url, { data })
.
initialize
hook 提供了一种定义自定义函数的方法,该函数在 hooks 模块初始化时在 hooks 线程中运行。当 hooks 模块通过 register
注册时,就会进行初始化。
¥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');
});
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');
});
register('./path-to-my-hooks.js', {
parentURL: pathToFileURL(__filename),
data: { number: 1, port: port2 },
transferList: [port2],
});