1

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?

Qiulang
  • 10,295
  • 11
  • 80
  • 129

2 Answers2

2

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.

Domenic
  • 110,262
  • 41
  • 219
  • 271
  • Thanks for the answer. I also have a feeling that the standard api always likes to keep a bit distance from the existing nodejs api. – Qiulang Dec 14 '22 at 09:53
0

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.

CMCDragonkai
  • 6,222
  • 12
  • 56
  • 98
  • 1
    Or you could just do `{ readable: new ReadableStream(), writable: new WritableStream() }`. This class is extra complicated for no real purpose. – Domenic Dec 14 '22 at 00:14
  • I needed the class for other reasons cause my stream contains other special states/properties. – CMCDragonkai Dec 14 '22 at 08:34