In NodeJS streams are the way to read data from source and write data to destination in continuous way. Streams is an EventEmitter instance and throws several events at different instance of times. Here in this article we will work on read and write streams in NodeJS.
In Node.js the streams are mostly using in real-time applications like chat app, graphical interface app, sending-receiving files, video-conferencing app, real-time location based apps, movies or songs streaming apps etc.
Types of Streams in NodeJS
- Readable Stream – Used for read operation
- Writable Stream – Used for write operation
- Duplex Stream – Used for read and write operation
- Transform Stream – It is a type of Duplex Stream where output is computed based on input
Commonly Used Events in NodeJS Stream
- data – This event is triggers when there is data available to read
- end – This event is triggers when there is no data to read
- error – This event is triggers when there is error in receiving and sending data
- finish – This event is triggers when all data has been flushed.
Now lets coding…
Step 1 : Create a file stream.js inside project directory in your local computer or server and paste the code given below
/*modules*/
var fs = require('fs');
/*modules*/
/*write stream*/
var data = 'Hello NodeJS';
var writeStream = fs.createWriteStream('output.txt');
writeStream.write(data, 'UTF8');
writeStream.end();
writeStream.on('finish', function(){
console.log('Writing Finished');
});
writeStream.on('error', function(err){
console.log(err.stack);
});
/*write stream*/
/*read stream*/
var inputData = '';
var readStream = fs.createReadStream('output.txt');
readStream.setEncoding('UTF8');
readStream.on('data', function(chunk){
inputData += chunk;
});
readStream.on('end', function(){
console.log('Reading Finished');
console.log(inputData);
});
readStream.on('error', function(err){
console.log(err.stack);
});
/*read stream*/
Step 2 : Run the below command and check the output in console and file created in project directory
node stream.js
That’s it we have done the read and write streams in NodeJS.
Recommended :
For more NodeJS Tutorials visit NodeJS page.
If you like this, share this.
Follow us on Facebook, Twitter, Tumblr, LinkedIn, YouTube.