Find your content:

Search form

Learn node.js simple way - Stream concepts

 
Share

What are Streams?

 

Streams are objects that allow you to read data from a source or write data to the destination in continuous manner.
 
In Node.js, there are four types of streams available.
 
Readable - For read operation
Writable - For write operation
Duplex   - Can be used for both read & write
Transform - Output is computed based on the input.
 
In Node.js most of the tasks are configured as events so streams also one of it. Each stream is an eventemitter instance and it has several events. I am listing out few here.
 
data  - This event is fired when there is data available to read.
error - This event is fired when there is any error receiving or writing data.
end   - This event is fired when there is no more data to read.
finish - This event is fired when all the data has been flushed to underlying system.

 

Read stream code example: ( Use the file test.txt which we created earlier)

var fs = require("fs"); // fs module is required to do the file operation
var data = '';

// Create a readable stream
var readStream = fs.createReadStream('test.txt'); // access file for streaming

// Set the encoding to be utf8. 
readStream.setEncoding('UTF8'); // Set the encoding which helps to get data in proper format

//Enable the data event which does the continuous read operation.
readStream.on('data', function(chunk) {
   data += chunk;
});

//Enable the end event which get called once all the data read is done.
readStream.on('end',function() {
   console.log(data);
});

//Enable the error event which will be called if any error occurred.

readStream.on('error', function(err) {
   console.log(err.stack);
});

console.log("Program Ended");

 

My Block Status

My Block Content