Advertisements

Read and Write Streams in NodeJS

Advertisements

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

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 :

Create URL in Node.js

Using events in Node.js

Upload file in Node.js

Create REST API in Node.js

For more NodeJS Tutorials visit NodeJS page.

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedInYouTube.