Cannot write to a stream after it has ended.
Production Risk
Medium. This error indicates a flaw in application logic related to data flow. While it may be caught, it suggests that some data is not being written as intended.
This error occurs when you attempt to call `.write()` on a writable stream after `.end()` has already been called on it. Once a stream is ended, it signals that no more data will be written. Any subsequent write attempts are invalid and result in this error, indicating a flaw in the stream handling logic.
- 1Calling `stream.write()` after `stream.end()` has been invoked.
- 2A race condition in asynchronous code where multiple parts of the application try to write to and end the same stream.
- 3Incorrectly reusing a stream that has already completed its lifecycle.
This error is thrown by a Writable stream instance when its `.write()` method is called but the stream has already been marked as finished.
const fs = require('fs');
const myStream = fs.createWriteStream('my-file.txt');
myStream.write('some data');
myStream.end(); // The stream is now ending.
try {
myStream.write('more data'); // This will throw.
} catch (err) {
console.error(err.code);
}expected output
ERR_STREAM_WRITE_AFTER_END
Fix 1
Ensure Writes Happen Before End
WHEN Writing data to a stream.
const fs = require('fs');
const myStream = fs.createWriteStream('my-file.txt');
function writeAllData(stream, dataArray) {
dataArray.forEach(chunk => {
stream.write(chunk);
});
stream.end(); // End the stream only after all data is written.
}
writeAllData(myStream, ['data1', 'data2']);Why this works
Structure your code so that all `stream.write()` calls are guaranteed to happen before the `stream.end()` call. Avoid calling `.end()` until you are certain no more data needs to be written.
Fix 2
Check if Stream is Destroyed
WHEN Interacting with a stream whose state is uncertain.
function safeWrite(stream, chunk) {
if (!stream.destroyed) {
stream.write(chunk);
} else {
console.log('Stream is destroyed, cannot write.');
}
}Why this works
Check the `stream.destroyed` boolean property. If it is `true`, the stream has been ended or encountered an error, and you should not attempt to write to it.
const fs = require('fs');
const myStream = fs.createWriteStream('my-file.txt');
myStream.write('some data');
myStream.end(); // The stream is now ending.
// this triggers ERR_STREAM_WRITE_AFTER_ENDtry {
// operation that may throw ERR_STREAM_WRITE_AFTER_END
riskyOperation()
} catch (err) {
if (err.code === 'ERR_STREAM_WRITE_AFTER_END') {
console.error('ERR_STREAM_WRITE_AFTER_END:', err.message)
} else {
throw err
}
}function safeWrite(stream, chunk) {
if (!stream.destroyed && !stream.writableEnded) {
stream.write(chunk)
}
}✕
https://github.com/nodejs/node/blob/main/lib/_stream_writable.js
More information ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev