Coordinate workers with a message channel
Coordinate workers with a message channel in Node.js: hand each worker one end of a MessageChannel so they talk directly. Node.js 24.
Two workers can exchange messages without the main thread relaying them. Create a MessageChannel and send one port to each worker.
import { Worker, MessageChannel, isMainThread, workerData, parentPort } from 'node:worker_threads';
if (isMainThread) {
const { port1, port2 } = new MessageChannel();
const ping = new Worker(new URL(import.meta.url), {
workerData: { role: 'ping', port: port1 },
transferList: [port1],
});
const pong = new Worker(new URL(import.meta.url), {
workerData: { role: 'pong', port: port2 },
transferList: [port2],
});
ping.once('message', (message) => console.log(message));
await Promise.all([ping, pong].map((w) => new Promise((resolve) => w.once('exit', resolve))));
console.log('both done');
} else {
const { role, port } = workerData;
if (role === 'ping') {
port.postMessage('ping');
port.once('message', (reply) => {
parentPort.postMessage(`ping heard ${reply}`);
port.close();
});
} else {
port.once('message', () => port.postMessage('pong'));
}
}ping heard pong
both doneA port must be listed in transferList to be moved to a worker. The ping worker sends first, pong answers, and ping reports to the main thread and closes its end, which also closes the other end so that pong can exit. The main thread never touches the messages between them.
Messages are copied with the structured clone algorithm. Pass a SharedArrayBuffer, or add the buffer to the transfer list, for large data. The module is described in the worker_threads docs.