a blog for those who code

Wednesday, 16 December 2015

Readable Streams in Nodejs

In this post we will be discussing about readable streams in Nodejs. Streams are one of the most important components of Node.js. Node.js is an event-based platform where the most efficient way to handle I/O is - consuming the input as soon as it is available and sending the output as soon as it is produced. So lets explore Streams in detail and understand how they can simplify I/O.

Every stream in Node.js is an implementation of one of the four base abstract classes available in the stream module stream.Readable, stream.Writable, stream.Duplex and stream.Transform. Readable streams let you read data from a source (Http server's request) while writable streams let you write data to a destination(Http server's response).

Readable Stream

A readable stream will let you read data from a source. This type of streams will emit readable events every time they get a chunk of data and they will emit end when they are all finished as shown below.

var fs = require('fs');
var streamRead = fs.createReadStream('file.txt');
var data = '';
var chunk;

streamRead.on('readable', function() {
  while((chunk = streamRead.read()) != null) {
    data += chunk;
  }
});

streamRead.on('end', function() {
 console.log('Stream Ended');
});

The read() function reads data from the internal buffer and returns it. When there is nothing it will return null. This is called non-flowing mode of reading data from stream. Using this approach, the data is explicitly pulled from the stream on demand. The data is read explicitly from within the readable listener, which is invoked as soon as new data is available.

ALSO READ : Difference between Buffering and Streaming in context of Nodejs

var fs = require('fs');
var streamRead = fs.createReadStream('file.txt');
var data = '';

streamRead.on('data', function(chunk) {
 data += chunk;
});

streamRead.on('end', function() {
 console.log('Stream Ended');
});

The above method is the flowing mode of reading the data from the stream. Readable streams can also be paused and resumed. Pause means stop emitting data events and resume means start emitting data again.

Note : By default the data is a Buffer object. You can change it using Readable.setEncoding() as shown below

var fs = require('fs');
var streamRead = fs.createReadStream('file.txt');
streamRead.setEncoding('utf8');

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

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License