8

What is the difference between 'close' and 'finish' events for NodeJS Writable stream?

If we suppose that we have a writable stream that write to disk, are both 'close' and 'finish' events activating after the data is persisted to the disk or not?

Nexx
  • 327
  • 4
  • 4

1 Answers1

9

With finish when all data is written to the stream but the stream may not be closed. After which a close will be emitted once file is closed. Hence finish will fire before close.

For example:

const writer = getWritableStreamSomehow();
for (let i = 0; i < 100; i++) {
    writer.write(`hello, #${i}!\n`);
}
writer.on('finish', () => {
    console.log('All data is written but file might NOT be closed');
});
writer.on('close', () => {
  console.log('All data written and file is closed');
});
writer.end('This is the end\n');

We can say writing a file involves Opening the file, Writting data to the File and Closing the file.

Finish will be emitted after finishing writing to the file and close after closing the file.

kg99
  • 746
  • 2
  • 14
  • 1
    If we have your example, when we write to a file in the disk, Is it possible a file to be written in the internal buffer of the writtable stream, but not saved to the disk yet, and 'finish' event to be emitted at that time (when the data is only in the memory, not in the disk)? – Nexx Nov 25 '20 at 14:59