Node.js – NodeJS: What’s the difference between a Duplex stream and a Transform stream

node.jsstream

The Stream docs state that Duplex Streams "are streams that implement both the Readable and Writable interfaces" and Transform Streams "are Duplex streams where the output is in some way computed from the input." Unfortunately, the docs do not describe what Transform streams provide above and beyond Duplex streams.

Are there any differences between the two? When would you use one over the other?

Best Answer

A Duplex stream can be thought of a readable stream with a writable stream. Both are independent and each have separate internal buffer. The reads and writes events happen independently.

                             Duplex Stream
                          ------------------|
                    Read  <-----               External Source
            You           ------------------|   
                    Write ----->               External Sink
                          ------------------|
            You don't get what you write. It is sent to another source.

A Transform stream is a duplex where the read and write takes place in a causal way. The end points of the duplex stream are linked via some transform. Read requires write to have occurred.

                                 Transform Stream
                           --------------|--------------
            You     Write  ---->                   ---->  Read  You
                           --------------|--------------
            You write something, it is transformed, then you read something.