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:
const fs = require( 'fs' );
const readable = fs.createReadStream( "input.txt" );
readable.on( 'readable' , () => {
let chunk;
while ( null !== (chunk = readable.read())) {
console.log(`read: ${chunk}`);
}
});
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:
const fs = require( 'fs' );
const readable = fs.createReadStream( "input.txt" );
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
Share your thoughts in the comments
Please Login to comment...