与模块定制钩子通信
¥Communication with module customization hooks
异步钩子在专用线程上运行,与运行应用代码的主线程分开。这意味着改变全局变量不会影响其他线程,并且必须使用消息通道在线程之间进行通信。
¥Asynchronous hooks run on a dedicated thread, separate from the main thread that runs application code. This means mutating global variables won't affect the other thread(s), and message channels must be used to communicate between the threads.
register
方法可用于将数据传递到 initialize
钩子。传递给钩子的数据可能包括可转移对象,如端口。
¥The register
method can be used to pass data to an initialize
hook. The
data passed to the hook may include transferable objects like ports.
import { register } from 'node:module';
import { MessageChannel } from 'node:worker_threads';
// This example demonstrates how a message channel can be used to
// communicate with the hooks, by sending `port2` to the hooks.
const { port1, port2 } = new MessageChannel();
port1.on('message', (msg) => {
console.log(msg);
});
port1.unref();
register('./my-hooks.mjs', {
parentURL: import.meta.url,
data: { number: 1, port: port2 },
transferList: [port2],
});
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 with the hooks, by sending `port2` to the hooks.
const { port1, port2 } = new MessageChannel();
port1.on('message', (msg) => {
console.log(msg);
});
port1.unref();
register('./my-hooks.mjs', {
parentURL: pathToFileURL(__filename),
data: { number: 1, port: port2 },
transferList: [port2],
});
同步模块钩子在运行应用代码的同一线程上运行。它们可以直接改变主线程访问的上下文的全局变量。
¥Synchronous module hooks are run on the same thread where the application code is run. They can directly mutate the globals of the context accessed by the main thread.