Open In App

Node.js Readable Stream end Event

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The ‘end’ Event in a Readable Stream is emitted when there is no available data to be consumed from the readable stream. And the ‘end’ event won’t be emitted if the data is not fully consumed. It can be done by switching the stream into the flowing mode, or by calling stream.read() method again and again until all the data is being consumed.

Syntax:

Event: 'end'

Below examples illustrate the use of end event in Node.js:

Example 1:




// Node.js program to demonstrate the     
// readable end event
  
// Including fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
  
// Instructions to read data
readable.on('readable', () => {
  let chunk;
  
  // Using while loop and calling
  // read method
  while (null !== (chunk = readable.read())) {
  
    // Displaying the chunk
    console.log(`read: ${chunk}`);
  }
});
  
// Handling end event
readable.on('end', () => {
  console.log('All the data is being consumed.');
});
  
console.log("Done...");


Output:

Done...
read: GeeksforGeeks
All the data is being consumed.

Example 2:




// Node.js program to demonstrate the     
// readable end event
  
// Including fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
  
// Handling end event
readable.on('end', () => {
  console.log('All the data is being consumed.');
});
  
console.log("Done...");


Output:

Done...

Here, all the data is not consumed as stream.read() method is not called so the end event is not emitted here.

Reference: https://nodejs.org/api/stream.html#stream_event_end



Last Updated : 12 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads