Instances of BroadcastChannel allow asynchronous one-to-many communication
with all other BroadcastChannel instances bound to the same channel name.
import { isMainThread, BroadcastChannel, Worker, } from 'node:worker_threads'; const bc = new BroadcastChannel('hello'); if (isMainThread) { let c = 0; bc.onmessage = (event) => { console.log(event.data); if (++c === 10) bc.close(); }; for (let n = 0; n < 10; n++) new Worker(new URL(import.meta.url)); } else { bc.postMessage('hello from every worker'); bc.close(); }
const { isMainThread, BroadcastChannel, Worker, } = require('node:worker_threads'); const bc = new BroadcastChannel('hello'); if (isMainThread) { let c = 0; bc.onmessage = (event) => { console.log(event.data); if (++c === 10) bc.close(); }; for (let n = 0; n < 10; n++) new Worker(__filename); } else { bc.postMessage('hello from every worker'); bc.close(); }
new BroadcastChannel(name): BroadcastChannel
Attributes
name:
anyThe name of the channel to connect to. Any JavaScript value
that can be converted to a string using
`${name}` is permitted.broadcastChannel.close(): void
Closes the BroadcastChannel connection.
Type:
FunctionInvoked with a single
MessageEvent argument
when a message is received.Type:
FunctionInvoked with a received message cannot be
deserialized.
broadcastChannel.postMessage(message): void
Attributes
message:
anyAny cloneable JavaScript value.
broadcastChannel.ref(): void
Opposite of unref(). Calling ref() on a previously unref()ed
BroadcastChannel 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.
broadcastChannel.unref(): void
Calling unref() on a BroadcastChannel allows the thread to exit if this
is the only active handle in the event system. If the BroadcastChannel is
already unref()ed calling unref() again has no effect.