Bun

class

worker_threads.MessagePort

class MessagePort

Instances of the worker.MessagePort class represent one end of an asynchronous, two-way communications channel. It can be used to transfer structured data, memory regions and other MessagePorts between different Workers.

This implementation matches browser MessagePort s.

  • type: string,
    callback: null | EventListenerOrEventListenerObject,
    options?: boolean | AddEventListenerOptions
    ): void;

    Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

    The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

    When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

    When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

    When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

    If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

    The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

    MDN Reference

    type: string,
    options?: boolean | AddEventListenerOptions
    ): void;

    Adds a new handler for the type event. Any given listener is added only once per type and per capture option value.

    If the once option is true, the listener is removed after the next time a type event is dispatched.

    The capture option is not used by Node.js in any functional way other than tracking registered event listeners per the EventTarget specification. Specifically, the capture option is used as part of the key when registering a listener. Any individual listener may be added once with capture = false, and once with capture = true.

  • event: 'close',
    listener: (ev: Event) => void
    ): this;

    Node.js-specific extension to the EventTarget class that emulates the equivalent EventEmitter API. The only difference between addListener() and addEventListener() is that addListener() will return a reference to the EventTarget.

    event: 'message',
    listener: (value: any) => void
    ): this;
    event: 'messageerror',
    listener: (error: Error) => void
    ): this;
    event: string,
    listener: (arg: any) => void
    ): this;
  • close(): void;

    Disables further sending of messages on either side of the connection. This method can be called when no further communication will happen over this MessagePort.

    The 'close' event is emitted on both MessagePort instances that are part of the channel.

  • event: Event
    ): boolean;

    Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

  • event: 'close',
    ev: Event
    ): boolean;

    Node.js-specific extension to the EventTarget class that dispatches the arg to the list of handlers for type.

    @returns

    true if event listeners registered for the type exist, otherwise false.

    event: 'message',
    value: any
    ): boolean;
    event: 'messageerror',
    error: Error
    ): boolean;
    event: string,
    arg: any
    ): boolean;
  • eventNames(): string[];

    Node.js-specific extension to the EventTarget class that returns an array of event type names for which event listeners are registered.

  • getMaxListeners(): number;

    Node.js-specific extension to the EventTarget class that returns the number of max event listeners.

  • hasRef(): boolean;

    If true, the MessagePort object will keep the Node.js event loop active.

  • type: string
    ): number;

    Node.js-specific extension to the EventTarget class that returns the number of event listeners registered for the type.

  • event: 'close',
    listener: (ev: Event) => void,
    options?: EventListenerOptions
    ): this;

    Node.js-specific alias for eventTarget.removeEventListener().

    event: 'message',
    listener: (value: any) => void,
    options?: EventListenerOptions
    ): this;
    event: 'messageerror',
    listener: (error: Error) => void,
    options?: EventListenerOptions
    ): this;
    event: string,
    listener: (arg: any) => void,
    options?: EventListenerOptions
    ): this;
  • event: 'close',
    listener: (ev: Event) => void
    ): this;

    Node.js-specific alias for eventTarget.addEventListener().

    event: 'message',
    listener: (value: any) => void
    ): this;
    event: 'messageerror',
    listener: (error: Error) => void
    ): this;
    event: string,
    listener: (arg: any) => void
    ): this;
  • event: 'close',
    listener: (ev: Event) => void
    ): this;

    Node.js-specific extension to the EventTarget class that adds a once listener for the given event type. This is equivalent to calling on with the once option set to true.

    event: 'message',
    listener: (value: any) => void
    ): this;
    event: 'messageerror',
    listener: (error: Error) => void
    ): this;
    event: string,
    listener: (arg: any) => void
    ): this;
  • value: any,
    transferList?: readonly Transferable[]
    ): 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 as RegExps, BigInts, Maps, Sets, etc.
    • value may contain typed arrays, both using ArrayBuffers and SharedArrayBuffers.
    • value may contain WebAssembly.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.

  • ref(): void;

    Opposite of unref(). Calling ref() on a previously unref()ed port does not let the program exit if it's the only active handle left (the default behavior). If the port is ref()ed, calling ref() again has no effect.

    If listeners are attached or removed using .on('message'), the port is ref()ed and unref()ed automatically depending on whether listeners for the event exist.

  • type?: string
    ): this;

    Node.js-specific extension to the EventTarget class. If type is specified, removes all registered listeners for type, otherwise removes all registered listeners.

  • type: string,
    callback: null | EventListenerOrEventListenerObject,
    options?: boolean | EventListenerOptions
    ): void;

    Removes the event listener in target's event listener list with the same type, callback, and options.

    MDN Reference

    type: string,
    options?: boolean | EventListenerOptions
    ): void;

    Removes the event listener in target's event listener list with the same type, callback, and options.

  • event: 'close',
    listener: (ev: Event) => void,
    options?: EventListenerOptions
    ): this;

    Node.js-specific extension to the EventTarget class that removes the listener for the given type. The only difference between removeListener() and removeEventListener() is that removeListener() will return a reference to the EventTarget.

    event: 'message',
    listener: (value: any) => void,
    options?: EventListenerOptions
    ): this;
    event: 'messageerror',
    listener: (error: Error) => void,
    options?: EventListenerOptions
    ): this;
    event: string,
    listener: (arg: any) => void,
    options?: EventListenerOptions
    ): this;
  • n: number
    ): void;

    Node.js-specific extension to the EventTarget class that sets the number of max event listeners as n.

  • start(): void;

    Starts receiving messages on this MessagePort. When using this port as an event emitter, this is called automatically once 'message' listeners are attached.

    This method exists for parity with the Web MessagePort API. In Node.js, it is only useful for ignoring messages when no event listener is present. Node.js also diverges in its handling of .onmessage. Setting it automatically calls .start(), but unsetting it lets messages queue up until a new handler is set or the port is discarded.

  • unref(): void;

    Calling unref() on a port allows the thread to exit if this is the only active handle in the event system. If the port is already unref()ed calling unref() again has no effect.

    If listeners are attached or removed using .on('message'), the port is ref()ed and unref()ed automatically depending on whether listeners for the event exist.