Separate message routes
Create a private communication path between two cooperating parts of an application.
Node.js · Class
MessageChannel creates an asynchronous, bidirectional communication channel in Node.js. Its two linked MessagePort endpoints let code exchange messages within a thread or across workers.
Constructing a MessageChannel creates two linked MessagePort objects. Messages posted through either port can be received asynchronously by the other, allowing communication within a thread or after transferring a port to another worker.
new MessageChannel()A MessageChannel object with port1 and port2 properties referencing linked MessagePort instances.
const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
port1.once('message', (message) => {
console.log(message);
port1.close();
port2.close();
});
port2.postMessage({ status: 'ready' });Creates two linked ports, sends a structured value through one, and receives it on the other.
Create a private communication path between two cooperating parts of an application.
Connect worker threads using a dedicated pair of transferable endpoints.
Exchange structured values asynchronously without sharing a single default message route.
MessageChannel creates an asynchronous, two-way communication channel. Its constructor returns port1 and port2, which are linked MessagePort instances used to send and receive messages.
Follow-up: How would you connect separate workers? Transfer one of the channel's MessagePort objects to another worker through an existing communication channel, then communicate over the transferred port.
It has no methods of its own. The channel exposes two linked ports, and each port provides the operational messaging interface.
Follow-up: Why create a custom channel instead of relying only on a worker's default channel? A custom channel separates communication paths and responsibilities between components.
Import MessageChannel from node:worker_threads and construct it with new MessageChannel(). The resulting port1 and port2 properties identify the linked endpoints.
Follow-up: What kind of data can the endpoints exchange? The related MessagePort API supports structured data, memory regions, and other MessagePort objects, subject to its transfer rules.
MessagePortWorkerparentPortworker_threads