Node.js | Readable Stream end Event

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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...");

chevron_right


Output:



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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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...");

chevron_right


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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.