Error Handling in Duplex and Transform
You'll learn how to properly catch and propagate errors in streams that both read and write data.
The Two-Sided Challenge
Duplex and Transform streams are unique because they have two independent sides: a readable side and a writable side. When an error occurs, you need to ensure it's handled on both sides and doesn't leave the stream in a broken state.
Think of a duplex stream like a two-way radio. If the microphone breaks (write side), you need to signal the speaker (read side) so the whole device shuts down cleanly—not just one half.
Propagating Errors Correctly
When you emit an error in either _read, _write, or _transform, you should:
const { Transform } = require('stream');
const errorProneTransform = new Transform({
transform(chunk, encoding, callback) {
try {
// Your transformation logic
if (chunk.toString().includes('BAD')) {
// Signal error via callback
return callback(new Error('Invalid data detected'));
}
this.push(chunk.toString().toUpperCase());
callback();
} catch (err) {
// Always pass errors to callback, never throw
callback(err);
}
}
});
errorProneTransform.on('error', (err) => {
console.error('Transform error:', err.message);
// Error propagates to both sides automatically
});
Key Principles
Never throw synchronously inside stream methods—always pass errors to the callback. This ensures the stream can clean up both sides properly. When an error is passed to the callback or emitted, Node.js automatically closes both the readable and writable sides, preventing memory leaks or hung streams.
Key Takeaway: In Duplex and Transform streams, always handle errors through callbacks rather than throwing, so errors propagate correctly and close both the read and write sides cleanly.