Node.js Writable Stream finish Event
Last Updated :
12 Oct, 2021
The ‘finish’ event in a Writable Stream is emitted after the Calling of writable.end() method when all the data is being flushed to the hidden system.
Syntax:
Event: 'finish'
Return Value: If the writable.end() method is being called before then this event is emitted else its not emitted.
Below examples illustrate the use of ‘finish’ event in Node.js:
Example 1:
const stream = require( 'stream' );
const writable = new stream.Writable({
write: function (chunk, encoding, next) {
console.log(chunk.toString());
next();
}
});
writable.write( 'hi' );
writable.end();
writable.on( 'finish' , function () {
console.log( "Write is completed." );
});
console.log( "program is ended." );
|
Output:
hi
program is ended.
Write is completed.
In the above example, writable.end() method is called before the finish event so it is emitted.
Example 2:
const stream = require( 'stream' );
const writable = new stream.Writable({
write: function (chunk, encoding, next) {
console.log(chunk.toString());
next();
}
});
writable.write( 'hi' );
writable.on( 'finish' , function () {
console.log( "Write is completed." );
});
console.log( "program is ended." );
|
Output:
hi
program is ended.
So, here writable.end() function is not called so the finish event is not executed.
Reference: https://nodejs.org/api/stream.html#stream_event_finish
Share your thoughts in the comments
Please Login to comment...