Node.js | Readable Stream readable Event

The ‘readable’ Event in a Readable Stream is emitted when the data is available so that it can be read from the stream or it can be emitted by adding a listener for the ‘readable’ event which will cause data to be read into an internal buffer.

Syntax:

Event: 'readable'

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

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:



Done...
read: GeeksforGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// readable event
  
// Including fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
  
// Handling readable event
readable.on('readable', () => {
  console.log(`readable: ${readable.read()}`);
});
  
// Handling end event
readable.on('end', () => {
  console.log('Stream ended');
});
console.log("Done.");

chevron_right


Output:

Done.
readable: GeeksforGeeks
readable: null
Stream ended

Here, end event is emitted so null is returned.

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




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.