Stream operation called after stream has finished
Production Risk
Common in async HTTP handlers; always check stream state before writing.
Thrown when a write or end operation is attempted on a Writable stream that has already emitted the finish event or been explicitly ended. Once a stream finishes, no more data can be written to it.
- 1Calling write() or end() after end() has already been called
- 2Async handler that writes to a response stream after it was already finalised
- 3Double-ending a stream in different code paths
Triggered when write() or end() is called on a Writable after its finish event has fired.
const { Writable } = require('stream');
const w = new Writable({ write(c, e, cb) { cb(); } });
w.end('done');
w.write('more'); // throws — stream already finishedexpected output
Error [ERR_STREAM_ALREADY_FINISHED]: write() after stream is finished
Fix
Guard writes with the writableFinished flag
WHEN In async handlers that may fire after the stream has ended
if (!stream.writableFinished && !stream.destroyed) {
stream.write(chunk);
}Why this works
Checking writableFinished prevents write calls on an already-ended stream.
const { Writable } = require('stream');
const w = new Writable({ write(c, e, cb) { cb(); } });
w.end('done');
w.write('more'); // throws — stream already finished // this triggers ERR_STREAM_ALREADY_FINISHEDtry {
// operation that may throw ERR_STREAM_ALREADY_FINISHED
riskyOperation()
} catch (err) {
if (err.code === 'ERR_STREAM_ALREADY_FINISHED') {
console.error('ERR_STREAM_ALREADY_FINISHED:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_stream_already_finished(...args) {
// validate args here
return performOperation(...args)
}✕ Write to a response or stream after calling end()
end() seals the stream; subsequent writes throw this error.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev