Node.js | Readable Stream data Event

The ‘data’ Event in a Readable Stream is emitted when readable.pipe() and readable.resume() method is called for switching the stream into the flowing mode or by adding a listener callback to the data event. This event can also be emitted by calling readable.read() method and returning the chunk of data available.

Syntax:

Event: 'data'

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

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// readable data 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 the data event
readable.on('data', (chunk) => {
  console.log(`chunk length is: ${chunk.length}`);
});
  
console.log("Done...");

chevron_right


Output:



Done...
chunk length is: 13
read: GeeksforGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// readable data event
  
// Including fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
   
// Calling pause method
readable.pause();
  
// Handling the data event
readable.on('data', (chunk) => {
  console.log(`chunk length is: ${chunk.length}`);
});
  
console.log("Done...");

chevron_right


Output:

Done...

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




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.