Stream

The stream has the most important role in Nodejs. A stream is an object and basically use to handle a large amount of data. Stream workflow “read from input and write to output in sequentially manner”.

There are 4 types of Stream

1) Readable:- this is basically use to read the data.

2) Writable:- this stream is used to write the data.

3) Duplex:- this stream is used to read and write in a sequence manner.

4) Transform:- this stream is used to read the data after that manipulating it and then generate new data.

some events of the stream

1) data:- this event is fired to read the data.

2) end:- this event is fired when no data is available to read.

3) error:- This event is fired when there is any error to read or write data.

4) finish:- This event is fired when all the data has been flushed to the underlying system.

Example:- if the file size is too large and we need to read data from the file then the fs.createReadStream method is useful because it will read the data from the file into chunk format.


var fs = require('fs');
var readableStream = fs.createReadStream('myfile.txt');
var data = '';

readableStream.on('data', function(chunkData) {
    data +=chunkData;
});

readableStream.on('end', function() {
    console.log(data);
});

Pipe:- through pipe() method we can read the data from one file and write the data into another file in a sequential manner.


var fs = require('fs');
var readableStream = fs.createReadStream('readFile.txt');
var writableStream = fs.createWriteStream('writeFile.txt');
readableStream.pipe(writableStream);