Skip to main content
BroadcastChannel - worker_threads - Node documentation
class BroadcastChannel

Usage in Deno

import { BroadcastChannel } from "node:worker_threads";

Instances of BroadcastChannel allow asynchronous one-to-many communication with all other BroadcastChannel instances bound to the same channel name.

'use strict';

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(__filename);
} else {
  bc.postMessage('hello from every worker');
  bc.close();
}

Constructors

new
BroadcastChannel(name: string)

Properties

readonly
name: string
onmessage: (message: unknown) => void

Invoked with a single `MessageEvent` argument when a message is received.

onmessageerror: (message: unknown) => void

Invoked with a received message cannot be deserialized.

Methods

close(): void

Closes the BroadcastChannel connection.

postMessage(message: unknown): void
interface BroadcastChannel
extends [NodeJS.RefCounted]
variable BroadcastChannel

BroadcastChannel class is a global reference for import { BroadcastChannel } from 'worker_threads' https://nodejs.org/api/globals.html#broadcastchannel

Type

globalThis extends { onmessage: any; BroadcastChannel: infer T; } ? T : _BroadcastChannel
Back to top