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:
javascript
Output:
javascript
Output:
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:
// Node.js program to demonstrate the
// finish event
// Including stream module
const stream = require('stream');
// Creating a stream and creating
// a write function
const writable = new stream.Writable({
// Write function with its
// parameters
write: function(chunk, encoding, next) {
// Converting the chunk of
// data to string
console.log(chunk.toString());
next();
}
});
// Writing data
writable.write('hi');
// Calling end function
writable.end();
// Emitting finish event
writable.on('finish', function() {
console.log("Write is completed.");
});
// Displays that the program
// is ended
console.log("program is ended.");
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:
// Node.js program to demonstrate the
// finish event
// Including stream module
const stream = require('stream');
// Creating a stream and creating
// a write function
const writable = new stream.Writable({
// Write function with its
// parameters
write: function(chunk, encoding, next) {
// Converting the chunk of
// data to string
console.log(chunk.toString());
next();
}
});
// Writing data
writable.write('hi');
// Emitting finish event
writable.on('finish', function() {
console.log("Write is completed.");
});
// Displays that the program
// is ended
console.log("program is ended.");
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