How do you correctly propagate and handle errors from a Node.js stream, given that stream errors aren't caught by a surrounding try/catch?
Short answer
Because streams are event-driven and much of their work happens asynchronously outside the synchronous call stack, wrapping stream operations in a try/catch doesn't catch errors emitted by the stream -- you must attach an explicit 'error' event listener to each stream in a…
Advertisement
AModel answer
Because streams are event-driven and much of their work happens asynchronously outside the synchronous call stack, wrapping stream operations in a try/catch doesn't catch errors emitted by the stream -- you must attach an explicit 'error' event listener to each stream in a pipeline, or use stream.pipeline() (rather than .pipe()), which properly propagates errors from any stream in the chain to a single callback or a rejected promise.
// try/catch does NOT catch this -- it's an async event, not a synchronous throw
try {
fs.createReadStream('missing-file.txt').pipe(res);
} catch (err) { /* never reached */ }
// Correct: explicit error listener, or use pipeline()
const { pipeline } = require('node:stream/promises');
try {
await pipeline(fs.createReadStream('missing-file.txt'), res);
} catch (err) {
console.error('Stream failed:', err.message); // correctly caught
}Real-world example
A file-download endpoint that silently hung whenever the source file didn't exist (because the error from createReadStream was never actually handled) was fixed by switching from .pipe() to stream.pipeline(), which properly surfaces the file-not-found error as a rejected promise the route handler can catch and respond to.
Likely follow-ups
- Why specifically does a try/catch fail to catch an error emitted asynchronously by an EventEmitter-based API like streams?
- What happens to a stream pipeline if one stream in the middle errors but the others don't have error listeners attached?
Related topics