Stream Events Reference
You'll learn the four key events that signal different stages of a stream's lifecycle and when each one fires.
Understanding Stream Events
Streams emit several important events that tell you what's happening during data processing. Think of these events like notifications at a train station: "train arriving," "train departing," "doors closing," and "station shutting down." Each event signals a specific moment in the stream's journey.
The Four Core Events
'end'
Fires on Readable streams when there's no more data to consume. This means the source has finished sending data, but the stream might still be processing what's already been received.
readableStream.on('end', () => {
console.log('No more data to read');
});
'finish'
Fires on Writable streams when all data has been flushed to the underlying system. This happens after you call stream.end() and everything has been written out.
writableStream.on('finish', () => {
console.log('All writes are complete');
});
'close'
Fires when the stream and its underlying resources (like file descriptors) are fully released. This happens after 'end' or 'finish', signaling complete cleanup.
stream.on('close', () => {
console.log('Stream resources released');
});
'error'
Fires whenever something goes wrong during stream operations. Always handle this event to prevent crashes.
stream.on('error', (err) => {
console.error('Stream error:', err);
});
Lifecycle Order
For a typical stream: 'error' (if problems occur) → 'end'/'finish' (data done) → 'close' (cleanup done).
Key Takeaway: Use 'end' for readable completion, 'finish' for writable completion, 'close' for final cleanup, and always handle 'error' to catch problems during any stream operation.