Besides `pipeline`, what is the `stream.finished` utility used for, and why is it important for preventing resource leaks?

Node.js interview question for Advanced practice.

Answer

stream.finished is a utility function that provides a reliable way to get a callback when a stream is no longer readable, writable, or has experienced an error or premature close event. It is important because listening for just the 'end' or 'finish' events is not sufficient to prevent resource leaks. A stream could be destroyed by an error or have its underlying resource close prematurely without ever emitting 'end' or 'finish'. stream.finished correctly handles all these terminal states. Example Use Case: Imagine you have a readable stream and you want to perform a cleanup action once it's completely done, no matter how it finished. javascript const { finished } = require('stream'); const fs = require('fs'); const readStream = fs.createReadStream('some-file.txt'); // ... do something with the stream ... finished(readStream, (err) = { if (err) { console.error('Stream failed!', err); } else { console.log('Stream is done. Performing cleanup.'); } // You can be sure the file descriptor is closed here. }); This prevents resource leaks by ensuring your cleanup code runs regardless of whether the stream completed successfully or failed.

Explanation

stream.finished is like a universal 'on-done' handler, working correctly whether a stream emits 'end', 'finish', 'error', or 'close'.

Related Questions