How to Fix ERR_STREAM_WRITE_AFTER_END in Node.js
ERR_STREAM_WRITE_AFTER_END in Node.js is raised when you call write() on a stream after you have closed it with end(). The fix is to finish all your writes and call end() last. If the data comes from an asynchronous operation, wait for that operation to finish before calling end().
This happens easily when you write CSV or log files with fs.createWriteStream(), or when you send an HTTP response, and the place where you call end() is far from the place where you call write(). I reproduced this error in a test environment and included the exact message it printed. After the fix, the error went away and every line was written to the file.
The test environment was Ubuntu 24.04 and Node.js 22.23.5. I received HTTP responses with curl. I replaced the working directory path in the output with /path/to/app. I did not test Windows, macOS, Node.js versions other than 22, or streams other than fs and http (such as net sockets or a custom Writable).
Reproducing the error
ERR_STREAM_WRITE_AFTER_END in the Node.js error list means that stream.write() was called after stream.end(). The writable.end() documentation also says that calling write() after end() produces this error.
The following write-after-end.mjs writes the last line with end() and then tries to write one more line.
// Calls write() again after end() has closed the stream
import fs from 'node:fs';
const out = fs.createWriteStream('log.txt');
out.write('1行目\n');
out.end('2行目\n');
out.write('3行目\n');
Running node write-after-end.mjs printed the following error and exited with code 1.
node:events:497
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at _write (node:internal/streams/writable:489:11)
at Writable.write (node:internal/streams/writable:510:10)
at file:///path/to/app/write-after-end.mjs:7:5
at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)
Emitted 'error' event on WriteStream instance at:
at emitErrorNT (node:internal/streams/destroy:170:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at process.processTicksAndRejections (node:internal/process/task_queues:89:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
Node.js v22.23.5
The node:internal lines are Node.js internals. The line that points to your own file (file:///…), write-after-end.mjs:7:5, is the write() call made after end(). Start by finding that line.
Unhandled 'error' event means the error was emitted as the stream's 'error' event and nothing was listening for it. As described in the error events documentation, if there is no 'error' listener, the error is thrown and the Node.js process exits.
In my test, log.txt was 0 bytes after this failure. Even the first and second lines that were written before the error did not remain. A script that fails with an error may not leave a partially written output file.
The fix is to finish all your writes and then call end() last. You can pass the final line to end().
// Finish all writes, then call end() last
import fs from 'node:fs';
const out = fs.createWriteStream('log.txt');
out.write('1行目\n');
out.write('2行目\n');
out.end('3行目\n');
After running this, the process exited with code 0, and log.txt contained the three lines from the first line to the third line.
When no error is shown and writes are dropped
A write() after end() does not always throw an error. The following async-write.mjs tries to load three items asynchronously and write them to a file as they arrive. However, it calls end() without waiting for the loads to finish.
// Calls end() without waiting for the async work
import fs from 'node:fs';
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
async function loadItem(id) {
await wait(100 * id); // stands in for an API call
return { id, name: `item-${id}` };
}
const out = fs.createWriteStream('items.txt');
for (const id of [1, 2, 3]) {
loadItem(id).then((item) => {
out.write(`${item.id},${item.name}\n`);
});
}
out.end();
The process exited with code 0 and no error was shown. However, items.txt was 0 bytes.
To see what was happening, I added a callback to the third argument of write() to receive any error. I also added a log just before each write that shows whether the stream had finished closing. writable.closed becomes true after the 'close' event has been emitted. As described in the writable.write() documentation, if a write fails, the error is passed as the first argument to this callback.
loadItem(id).then((item) => {
console.log(`id ${id} を書く。closed: ${out.closed}`);
out.write(`${item.id},${item.name}\n`, (err) => {
if (err) console.error(`id ${id} を書けなかった:`, err.code, err.message);
});
});
id 1 を書く。closed: true
id 1 を書けなかった: ERR_STREAM_WRITE_AFTER_END write after end
id 2 を書く。closed: true
id 2 を書けなかった: ERR_STREAM_WRITE_AFTER_END write after end
id 3 を書く。closed: true
id 3 を書けなかった: ERR_STREAM_WRITE_AFTER_END write after end
All three writes received ERR_STREAM_WRITE_AFTER_END in the callback. As closed: true shows, the stream had already finished closing by the time the first item arrived. In the first example, write() was called right after end(), before the stream had finished closing, so the 'error' event fired and the process stopped. In a different script that calls write() after the stream has fully closed (after the 'close' event), no 'error' event fired and the error was only passed to the callback. Since nothing is logged for writes after the stream has closed, you will not notice the problem until you check the contents of the output file.
The fix is to wait for all the loads to finish, write the results, and then call end(). You can wait for the stream to finish by awaiting finished() from node:stream/promises.
// Wait for all work, then write and call end() last
import fs from 'node:fs';
import { finished } from 'node:stream/promises';
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
async function loadItem(id) {
await wait(100 * id); // stands in for an API call
return { id, name: `item-${id}` };
}
const out = fs.createWriteStream('items.txt');
const items = await Promise.all([1, 2, 3].map(loadItem));
for (const item of items) {
out.write(`${item.id},${item.name}\n`);
}
out.end();
await finished(out);
console.log('items.txt に書き終えた');
The script printed items.txt に書き終えた ("Finished writing items.txt"), and items.txt contained these three lines:
1,item-1
2,item-2
3,item-3
Closing a stream that a timer keeps writing to
The same problem happens when you write logs at a fixed interval and close the stream on Ctrl+C (SIGINT). The following timer-write.mjs closes the stream when it receives SIGINT, but it does not stop the timer that writes to it.
// Writes a log line every second and closes the stream on Ctrl+C (SIGINT)
import fs from 'node:fs';
const out = fs.createWriteStream('ticks.txt');
let n = 0;
setInterval(() => {
out.write(`tick ${++n}\n`);
}, 1000);
process.on('SIGINT', () => {
console.log('SIGINT を受け取った');
out.end('stop\n');
});
I started the script and sent SIGINT after 2.5 seconds. ticks.txt contained tick 1, tick 2, and stop. The process did not exit, because the timer was still running. It was still running 2.5 seconds after SIGINT was sent. Each write() from the third one onward was silently dropped without an error.
The fix is to stop the timer that writes to the stream before you close the stream. Store the return value of setInterval() in timer, and call clearInterval() when SIGINT is received.
process.on('SIGINT', () => {
console.log('SIGINT を受け取った');
clearInterval(timer);
out.end('stop\n', () => console.log('ticks.txt を閉じた'));
});
When I sent SIGINT again, the script printed ticks.txt を閉じた ("Closed ticks.txt") and the process exited on its own with code 0.
If you cannot stop the writer, for example when several places write to the same log stream, check writable.writableEnded before each write. writableEnded becomes true once end() has been called.
setInterval(() => {
if (out.writableEnded) {
console.log('end() のあとなので書かない');
return;
}
out.write(`tick ${++n}\n`);
}, 1000);
When I tested this, after SIGINT the script printed end() のあとなので書かない ("Not writing because end() has already been called") and did not write anything. However, the timer kept running, so the process did not exit. To let the process exit, you still need to stop the timer.
HTTP responses: no crash, but the later data never arrives
The http response object (res) also has write() and end(), the same as a writable stream. The following http-write-after-end.mjs calls res.write() inside a timer after it has already sent the response with res.end().
// Calls write() in a timer after the response was already sent with end()
import http from 'node:http';
const server = http.createServer((req, res) => {
res.end('ok\n');
setTimeout(() => {
const ok = res.write('more\n', (err) => {
console.log('write のコールバック:', err?.code, err?.message);
});
console.log('write() の戻り値:', ok);
}, 100);
});
server.listen(3000, () => console.log('listening on 3000'));
The response I received with curl contained only ok, and more never arrived. The server did not crash. The output was:
listening on 3000
write() の戻り値: false
write のコールバック: ERR_STREAM_WRITE_AFTER_END write after end
Again, the error was only passed to the callback. If part of a response is missing and nothing is logged, look for a res.write() call that comes after res.end(). Only call res.end() once you have finished writing all the content. If there is any chance that a response was already sent earlier, you can check whether end() has already been called with response.writableEnded.




