Bare Docs

bare-broadcast-channel

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

Documented against v0.2.1
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)

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?BroadcastChannelOptions—Channel 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

Restore a channel from its SharedArrayBuffer handle.

Parameters

ParameterTypeDefaultDescription
handleSharedArrayBuffer—The SharedArrayBuffer backing the channel, as exposed by channel.handle.
opts?BroadcastChannelOptions—The same options as the constructor, except handle.

Returns BroadcastChannel — A channel backed by the given handle.

BroadcastChannel.MAX_PORTS: number

Maximum number of ports that may be concurrently connected to a single channel. A port's slot is released for reuse by a later connection once the port has fully torn down.

connect(): Port<T>

Connect a new port to the channel. Throws if MAX_PORTS ports are already connected. Port slots are reused, so the cap applies to the number of concurrently connected ports, not the total number of connections over the channel's lifetime; a slot is released for a later connection once the port holding it has fully torn down.

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

handle: SharedArrayBuffer

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

interfaces: SerializableConstructor[]

The serializable and transferable interfaces registered on the channel.

Port

new Port(channel: BroadcastChannel<T>)

Create a new port connected to channel, equivalent to channel.connect(). Throws if MAX_PORTS ports are already connected.

Parameters

ParameterTypeDefaultDescription
channelBroadcastChannel<T>—The channel to connect the port to.

close(): Promise<void>

Close the port, waiting for any pending write to drain first. The port leaves the channel and its slot is released for reuse once it has fully torn down.

Returns Promise<void> — A promise that resolves once the port has closed.

createReadStream(opts?: ReadableOptions<Port<T>>): Readable

Parameters

ParameterTypeDefaultDescription
opts?ReadableOptions<Port<T>>—The same options as bare-stream's Readable.

Returns Readable — A readable stream of the messages read from the port.

createStream(opts?: DuplexOptions<Port<T>>): Duplex

Parameters

ParameterTypeDefaultDescription
opts?DuplexOptions<Port<T>>—The same options as bare-stream's Duplex.

Returns Duplex — A duplex stream that reads the messages broadcast to the port and writes its chunks to the port. The port is closed when the stream ends.

createWriteStream(opts?: WritableOptions<Port<T>>): Writable

Parameters

ParameterTypeDefaultDescription
opts?WritableOptions<Port<T>>—The same options as bare-stream's Writable.

Returns Writable — A writable stream whose chunks are written to the port. The port is closed when the stream ends.

peers: number

The number of other ports currently connected to the channel. Read-only.

read(): Promise<T | null>

Read the next message broadcast to the port, waiting for one to arrive if none is queued.

Returns Promise<T | null> — The next message, or null if the port has ended or every peer has left and the remaining messages have been read.

readSync(): T | null

Read the next message broadcast to the port, blocking the thread if none is queued.

Returns T | null — The next message, or null if the port has ended or every peer has left and the remaining messages have been read.

ref(): void

Increase the reference count for the port to keep the event loop alive. Does nothing once the port has started closing.

unref(): void

Decrease the reference count for the port to allow the event loop to exit. Does nothing once the port has started closing.

write(value: T): Promise<boolean>

Write value to every other port connected to the channel, waiting for room if any of them is full. A port never receives the messages it wrote itself.

Parameters

ParameterTypeDefaultDescription
valueT—A structured-cloneable value to broadcast to peers.

Returns Promise<boolean> — true once the value has been broadcast, or false if value is null or the port is closing or has ended.

writeSync(value: T): boolean

Write value to every other port connected to the channel, blocking the thread if any of them is full. A port never receives the messages it wrote itself.

Parameters

ParameterTypeDefaultDescription
valueT—A structured-cloneable value to broadcast to peers.

Returns boolean — true once the value has been broadcast, or false if value is null or the port has ended.

Types

BroadcastChannelOptions

interface BroadcastChannelOptions {
  handle?: SharedArrayBuffer
  interfaces?: SerializableConstructor[]
  portCapacity?: number
}

PortEvents

interface PortEvents {
  peers: [count: number]
  close: []
}

See also

  • Builds on bare-events, bare-stream, and bare-structured-clone.
  • Bare modules — the full bare-* catalog.
  • Bare runtime API — the runtime these modules extend.

Last updated on

Was this helpful?

On this page