LogoPear Docs
ReferencesBareModules

bare-broadcast-channel

Multi-producer, multi-consumer inter-thread broadcast messaging for JavaScript

stable

bare-broadcast-channel — Multi-producer, multi-consumer inter-thread broadcast messaging for JavaScript. It is a native addon.

npm i bare-broadcast-channel

Usage

const BroadcastChannel = require('bare-broadcast-channel')
const { Thread } = Bare

const channel = new BroadcastChannel()

const consumer = (label) =>
  new Thread(__filename, { data: { handle: channel.handle, label } }, async ({ handle, label }) => {
    const BroadcastChannel = require('bare-broadcast-channel')
    const port = BroadcastChannel.from(handle).connect()
    console.log(label, 'got', await port.read())
    await port.close()
  })

const a = consumer('a')
const b = consumer('b')

const port = channel.connect()

while (port.peers < 2) await new Promise((r) => setTimeout(r, 10))

await port.write('hello')
await port.close()

a.join()
b.join()

API

BroadcastChannel

new BroadcastChannel(opts?: BroadcastChannelOptions)

Source

Create a new broadcast channel. The channel is backed by a SharedArrayBuffer exposed as channel.handle that can be passed to other threads to share the channel across them.

Parameters

ParameterTypeDefaultDescription
opts?BroadcastChannelOptionsChannel options; handle backs the channel with an existing SharedArrayBuffer, interfaces registers serializable and transferable interfaces (default []), and portCapacity defaults to 1024.

BroadcastChannel.from

BroadcastChannel.from(handle: SharedArrayBuffer, opts?: BroadcastChannelOptions): BroadcastChannel
Source

Restore a channel from its SharedArrayBuffer handle. options accepts the same fields as the constructor, except for handle.

Parameters

ParameterTypeDefaultDescription
handleSharedArrayBufferThe SharedArrayBuffer backing the channel, as exposed by channel.handle.
opts?BroadcastChannelOptionsThe same options as the constructor, except handle.

Returns BroadcastChannel — A channel backed by the given handle.

BroadcastChannel.MAX_PORTS: number

Source

Maximum number of ports that may connect to a single channel over its lifetime.

connect(): Port<T>

Source

Connect a new port to the channel. Throws if MAX_PORTS has been reached. Port slots are not reused, so the cap applies to the total number of connections over the channel's lifetime, not the number of concurrently connected ports.

Returns Port<T> — A new port connected to the channel.

handle: SharedArrayBuffer

Source

The SharedArrayBuffer backing the channel. Pass this to other threads to share the channel.

interfaces: SerializableConstructor[]

Source

The serializable and transferable interfaces registered on the channel.

See also

On this page