Related Articles

Related Articles

Node.js | Writable Stream finish Event
  • Last Updated : 05 Mar, 2020

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:



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.");

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.");

chevron_right


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




My Personal Notes arrow_drop_up
Recommended Articles
Page :