Usage in Deno
import { MessagePort } from "node:worker_threads";
MessagePort.prototype.postMessage(value: any,transferList?: readonly TransferListItem[],): void
Sends a JavaScript value to the receiving side of this channel. value
is transferred in a way which is compatible with
the HTML structured clone algorithm.
In particular, the significant differences to JSON
are:
value
may contain circular references.value
may contain instances of builtin JS types such asRegExp
s,BigInt
s,Map
s,Set
s, etc.value
may contain typed arrays, both usingArrayBuffer
s andSharedArrayBuffer
s.value
may containWebAssembly.Module
instances.value
may not contain native (C++-backed) objects other than:
import { MessageChannel } from 'node:worker_threads'; const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log(message)); const circularData = {}; circularData.foo = circularData; // Prints: { foo: [Circular] } port2.postMessage(circularData);
transferList
may be a list of ArrayBuffer
, MessagePort
, and FileHandle
objects.
After transferring, they are not usable on the sending side of the channel
anymore (even if they are not contained in value
). Unlike with child processes
, transferring handles such as network sockets is currently
not supported.
If value
contains SharedArrayBuffer
instances, those are accessible
from either thread. They cannot be listed in transferList
.
value
may still contain ArrayBuffer
instances that are not in transferList
; in that case, the underlying memory is copied rather than moved.
import { MessageChannel } from 'node:worker_threads'; const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log(message)); const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]); // This posts a copy of `uint8Array`: port2.postMessage(uint8Array); // This does not copy data, but renders `uint8Array` unusable: port2.postMessage(uint8Array, [ uint8Array.buffer ]); // The memory for the `sharedUint8Array` is accessible from both the // original and the copy received by `.on('message')`: const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4)); port2.postMessage(sharedUint8Array); // This transfers a freshly created message port to the receiver. // This can be used, for example, to create communication channels between // multiple `Worker` threads that are children of the same parent thread. const otherChannel = new MessageChannel(); port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
The message object is cloned immediately, and can be modified after posting without having side effects.
For more information on the serialization and deserialization mechanisms
behind this API, see the serialization API of the node:v8 module
.
transferList: readonly TransferListItem[]
void