Why does Web Streams API lack Duplex Stream?

386 views Asked by At

I am familiar with the "old" nodejs stream, so the need of Duplex steam "streams that are both Readable and Writable (for example, net.Socket)" seem quite obvious.

To quote

Examples of Duplex streams include:

  1. TCP sockets
  2. zlib streams
  3. crypto streams

When I am studying nodejs18 new features and find nodejs has added Web Streams API. I was a bit surprised to see web streams only has 3 steam types, i.e. it lacks of Duplex stream. I notice it is because https://streams.spec.whatwg.org/ only defines 3 types of streams. But why ? Doesn't the need for a both Readable and Writable stream obvious?

2

There are 2 answers

2
CMCDragonkai On

I was just looking into this right now, and yes there's no equivalent to Duplex for the web streams, however you create your own by doing something like this:

class MyStream<R = any, W = any> implements ReadableWritablePair<R, W> {
  public readable: ReadableStream<R>;
  public writable: WritableStream<W>;
  public constructor() {
    this.readable = new ReadableStream();
    this.writable = new WritableStream();
  }
}

Then implement each side independently.

1
Domenic On

A duplex stream is any object with a readable property that is a ReadableStream, and a writable property that is a WritableStream. Since it is easy to create objects with two properties in JavaScript (use the syntax { readable, writable }), there is no need for a class or other helper. So the standard does not include one.

The standard gives more information on this in https://streams.spec.whatwg.org/#other-specs-duplex.