Read and Write Streams in NodeJS

Read and Write Streams in NodeJS

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

var fs = require('fs');

/*write stream*/
var data = 'Hello NodeJS';
var writeStream = fs.createWriteStream('output.txt');

writeStream.write(data, 'UTF8');


writeStream.on('finish', function(){
	console.log('Writing Finished');

writeStream.on('error', function(err){
/*write stream*/

/*read stream*/
var inputData = '';
var readStream = fs.createReadStream('output.txt');


readStream.on('data', function(chunk){
	inputData += chunk;

readStream.on('end', function(){
	console.log('Reading Finished');

readStream.on('error', function(err){

/*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.

Author: ReadyMadeCode is a website where you can find Free Online Tutorials - Website Development Tutorials, App Development Tutorials, Coding Tutorials,Website Designing and Development From popular programming languages or scripts or framework like php, laravel, html, css, javascript, nodejs, java, angularjs etc. Download Emails | E-Books.

View All Posts From ReadyMadeCode
Author Website :
Scroll to top

Subscribe For Latest Updates

Enter your email address to subscribe and receive notifications of posts & updates by email.

Want a Website / App / Digital Marketing Solution

Website & App Development Packages

%d bloggers like this:
We have updated our memberships. Please check here
Close X