On this page

Duplex channels

History
M

duplex

History
duplex(options?): Array
Attributes
options:Object
budget?:number
Buffer size in bytes for both directions. Default: 16384.
backpressure?:string
Policy for both directions. Default: 'strict'.
Cancellation signal for both channels.
Options specific to the A-to-B direction. Overrides shared options.
budget:number
backpressure:string
Options specific to the B-to-A direction. Overrides shared options.
budget:number
backpressure:string
Returns:Array
A pair [channelA, channelB] of duplex channels.

Create a pair of connected duplex channels for bidirectional communication, similar to socketpair(). Data written to one channel's writer appears in the other channel's readable.

Each channel has:

  • writer — a [Writer interface][] object for sending data to the peer.
  • readable — an AsyncIterable for reading data from the peer.
  • close() — close this end of the channel (idempotent).
  • [Symbol.asyncDispose]() — async dispose support for await using.
import { duplex, text } from 'node:stream/iter';

const [client, server] = duplex();

// Server echoes back
const serving = (async () => {
  for await (const chunks of server.readable) {
    await server.writer.writev(chunks);
  }
})();

await client.writer.write('hello');
await client.writer.end();

console.log(await text(server.readable)); // handled by echo
await serving;
const { duplex, text } = require('node:stream/iter');

async function run() {
  const [client, server] = duplex();

  // Server echoes back
  const serving = (async () => {
    for await (const chunks of server.readable) {
      await server.writer.writev(chunks);
    }
  })();

  await client.writer.write('hello');
  await client.writer.end();

  console.log(await text(server.readable)); // handled by echo
  await serving;
}

run().catch(console.error);