继承自 EventTarget 的 BroadcastChannel 类


稳定性: 1 - 实验

BroadcastChannel 的实例允许与绑定到相同通道名称的所有其他 BroadcastChannel 实例进行异步的一对多通信。

'use strict';

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();
}

Stability: 1 - Experimental

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

'use strict';

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();
}