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:
const fs = require( 'fs' );
const readable = fs.createReadStream( "input.txt" );
readable.on( 'readable' , () => {
let chunk;
while ( null !== (chunk = readable.read())) {
console.log(`read: ${chunk}`);
}
});
console.log( "Done..." );
|
Output:
Done...
read: GeeksforGeeks
Example 2:
const fs = require( 'fs' );
const readable = fs.createReadStream( "input.txt" );
readable.on( 'readable' , () => {
console.log(`readable: ${readable.read()}`);
});
readable.on( 'end' , () => {
console.log( 'Stream ended' );
});
console.log( "Done." );
|
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
Last Updated :
12 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...