Node.js streams are nothing but instances of eventEmitter class. Streams are used to write data to different destinations and read data from different destinations. There are four types of node.js streams.
As discussed earlier, Streams are instances of eventEmitter class. This means that node.js streams can fire events. Following are some of the events that stream classes can fire.
To see how stream objects read data from some source, take a look at the following example.
Create a text file named “myfile.txt” and add the following text in the file.
Knowledge hills is a website that contains free of cost programming tutorials
Learn and Build apps for free.
Now create a file named “streams.js” in the same directory as “myfile.txt” and add the following line of code in it.
var filestream = require("fs");
var contents = '';
var rstream = filestream.createReadStream('myfile.txt');
rstream.setEncoding('UTF8');
rstream.on('data', function(data) {
contents += data;
});
rstream.on('end',function(){
console.log(contents);
});
rstream.on('error', function(err){
console.log(err.stack);
});
rstream.on('finish', function(){
console.log("Data reading complete");
});
console.log("Code After File Reading.");
In the above code, we import “fs” module. We then call readFileStream() function on the object and pass it the path of the file. This gives us instance of readable stream. Next, we bind data, end and error events. Whenever data event occurs, we add newly read data to already read data stored in the content variable. When data reading is complete, we display the content variable. When you run the code you shall see that the line of code after data reading functionality shall be displayed first. This is because data reading is an asynchronous task and runs in parallel with other piece of code.
Now, you know how to read data via streams. Writing data via streams is also very similar. Take a look at the following example.
var filestream = require("fs");
var content = 'Knowledge Hills, Learning Platform';
var wStream = filestream.createWriteStream('output.txt');
wStream.write(content,'UTF8');
wStream.end();
wStream.on('finish', function() {
console.log("Content Writing Completed");
});
wStream.on('error', function(error){
console.log(error.stack);
});
console.log("Code After Data Writing");
Now when you execute the above code, you shall see that a file named “output.txt” will be created in the root directory of the code file. The file shall contain the string “Knowledge Hills, Learning Platform”. In the above code we used “createWriteStream” function which returns a writable stream.