Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Web APIs in Node.js

Node.js MessageChannel and MessagePort

Reference for MessageChannel and MessagePort in Node.js: create a pair of connected ports, post structured-clone messages, transfer buffers and close cleanly.

A MessageChannel creates two connected MessagePort objects, port1 and port2. Whatever you send with postMessage() on one port arrives as a message event on the other. Messages are copied with the structured clone algorithm, so you can send objects, arrays, Map, Set, Date, typed arrays and more, but not functions.

The classes are globals, as in browsers, and they are also exported from node:worker_threads. Their main job is to connect threads: you can transfer a port to a Worker and talk to it over a private line. They work inside one thread too, which makes them handy for experiments.

NODE
const { port1, port2 } = new MessageChannel();
port1.onmessage = (event) => console.log(event.data);
port2.postMessage('hi');

Try it

Node.js Sending messages both ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Transferring a buffer and cloning errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
const channel = new MessageChannel();
channel.port1;   // MessagePort
channel.port2;   // MessagePort

port.postMessage(value[, transferList]);
port.postMessage(value[, options]);   // options.transfer: array
port.on('message', (value) => {});    // or port.onmessage = (event) => {}
port.start();
port.close();
port.ref();
port.unref();
Name Description
value Any structured-cloneable value.
transferList Objects to move instead of copy: ArrayBuffer, MessagePort and a few others. A transferred ArrayBuffer becomes detached (length 0) in the sender.
port.start() Begins dispatching queued messages. Called automatically when you add a message listener or set onmessage.
port.close() Disconnects the port and its partner. Both emit close.
port.ref() / port.unref() Control whether the open port keeps the process alive.

Events: with on() the listener receives the cloned value directly; with the web-style onmessage or addEventListener('message', ...) it receives a MessageEvent whose data property holds the value. A messageerror event fires when a message cannot be deserialized.

Errors: postMessage() throws a DataCloneError (a DOMException) when the value cannot be cloned, for example a function or a symbol.

Usage notes

  • Messages are copies. Changing an object after sending it does not affect what the other side receives. Only transferred objects move.
  • Ports keep the process alive. A port with a message listener holds the event loop open until it is closed or unref()ed. A script that never calls close() will not exit on its own.
  • Closing one end closes both. After port.close(), both ports emit close and further messages are dropped.
  • Messages sent before a listener exists wait. They queue until the port is started, so the first message is not lost.
  • Ports can be transferred. Pass a port in the transferList of another port or of worker.postMessage() to hand a private channel to a worker. Once transferred, you cannot use it in the sender.
  • Use receiveMessageOnPort() from node:worker_threads for a synchronous read of one queued message without listeners.
  • BroadcastChannel is the one-to-many variant: every instance with the same name receives every message.
  • Not for networking. Ports only connect threads inside one Node.js process.