Duplex Streams
Learn how Duplex streams work.
A Duplex
stream is a stream that is both Readable
and Writable
. It’s useful when we want to describe an entity that’s both a data source and a data destination, such as network sockets. Duplex
streams inherit the methods of both stream.Readable
and stream.Writable
, so this is nothing new to us. This means that we can read()
or write()
data, or listen for both readable
and drain
events.
To create a custom Duplex
stream, we have to provide an implementation for both _read()
and _write()
. The options object passed to the Duplex()
constructor is internally forwarded to both the Readable
and Writable
constructors. The options are the same as those we’ve already discussed in the previous sections, with the addition of a new one called allowHalfOpen
(defaults to true
) that, if set to false
, will cause both parts (Readable
and Writable
) of the stream to end if only one of them does.
Get hands-on with 1400+ tech skills courses.