Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js Streams: 'close' vs 'finish' event

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?

like image 788
Nexx Avatar asked Feb 27 '26 00:02

Nexx


1 Answers

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.

like image 59
kg99 Avatar answered Feb 28 '26 14:02

kg99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!