a blog for those who code

Wednesday 23 December 2015

Duplex Streams in Node.js

In this post we will be discussing about Duplex streams in Node.js. A duplex stream is a stream that is both Readable and Writable. It refers to a stream which actually has two full independent streams embedded in it, one for incoming and one for outgoing. Before knowing duplex streams, you should know Readable Streams and Writable Streams.

A Duplex stream  is useful when you want to describe an entity both a data source and a data destination for example network sockets. A socket is build as a duplex stream to implement two independent channels (one for sending data and one for receiving data). Duplex streams inherit the methods of both stream.Readable and stream.Writable, thus we can read() and write() data, or listen to both readable and writable events as shown below.


When creating Duplex Streams you can also provide an options (object passed to both Writable and Readable constructors). It has following fields :

1. allowHalfOpen - Default=true. If set to false then stream will automatically end the readable side when the writable side ends and vice versa.
2. readableObjectMode - Default=false. It sets objectMode for readable side of the stream.
3. writableObjectMode - Default=false. It sets objectMode for writable side of the stream.

Create Duplex Stream

var Duplex = require('stream').Duplex;
var fs = require('fs');

Duplex.Readable = fs.createReadStream('example.txt');
Duplex.Writable = fs.createWriteStream('test2.txt');
Duplex.Readable.setEncoding('utf8');

Duplex.Readable.on('data', function(chunk) {
  Duplex.Writable.write(chunk);
});

It is not the actual way how you will create Duplex, this is just to give you an idea that how Duplex stream works. In the above code we have created a writable and readable stream in the same object which reads and writes to another file. The contents of Duplex object is shown below :


Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment