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?
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?
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.