Streams are objects, which are use to read/write operation from or to a file. There are four types of streams.
Readable - used for read file. Writable -used for write file.
Duplex - used for both read and write a file.
Transform – Its type of duplex stream where the output is computed based on input.
The stream is an EventEmitter instance and triggers several events at a different instance of times.
These events like data, end, error, finish which commonly used.
data - Triggered when there is data is available to read.
end - Triggered when there is no more data to read.
error - Triggered when there is any error receiving.
finish - Triggered when all data has been flushed to the underlying system.
These above operations are commonly used on NodeJs stream.
Readable Stream example:
let's create a js file named test.js as below:
var fs = require("fs");
var data = '';
//readable stream
var readerStream = fs.createReadStream('test.txt');
//encoding to utf8.
readerStream.setEncoding('UTF8');
// Handle stream events i.e.data, end, and error
readerStream.on('data', function(chunk) {
data += chunk;
});
readerStream.on('end',function(){
console.log(data);
});
readerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program is Ended");
And another file as test.txt like
Data Intensive Real time Applications (DIRT)
Data Streaming Applications
JSON APIs based Applications
Single Page Applications
Now run the test.js on NodeJs.REPL by command:
$ nodejs test.js
The Output is :
Program is Ended
Data Intensive Real time Applications (DIRT)
Data Streaming Applications
JSON APIs based Applications
Single Page Applications
0 Comment(s)