Skip to content
jshacks.dev
Async

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.

1 min read
Summarize in AI

Two workers can exchange messages without the main thread relaying them. Create a MessageChannel and send one port to each worker.

ping-pong.mjsJavaScript
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'));
  }
}
Text
ping heard pong
both done

A 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.

Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.