Writing to a file stream throws 'write after end' in Node.js
Fix it fast
Most common cause, 1 of 3end() runs before the async writes are done
Use a plain for...of loop so each await finishes before the next row.
import { createWriteStream } from 'node:fs';
import { once } from 'node:events';
const out = createWriteStream('report.csv');
for (const row of rows) {
const line = await formatRow(row);
if (!out.write(line + '\n')) await once(out, 'drain');
}
out.end();
await once(out, 'finish');Short answer
ERR_STREAM_WRITE_AFTER_END on an fs.createWriteStream file means write() ran after end(). In Node.js 22 to 26 the usual triggers are end() called before awaited writes finish, pipe() ending the target when its source ends, or a module-level stream reused after an earlier job closed it. Finish every write, then call end() once, or let pipeline() close the file.
Which cause do you have?
Wrap your writes in a small helper that reports the stream state. writableEnded becomes true as soon as end() is called, so the first trace printed points at the write that comes too late, and the stack shows who made it.
const write = (stream, chunk) => {
if (stream.writableEnded) console.trace('late write: end() was already called');
return stream.write(chunk);
};Then find the line you see in this list and open its fix:
- 1end() runs before the async writes are done
The writes happen inside forEach(async ...), .then() callbacks or event handlers, and end() sits right after them - 2pipe() ended the target when its source finished
Writes made after src.pipe(out) fail once src has emitted end - 3A shared stream was ended by an earlier job
The first export, request or test passes; every later one in the same process fails at once
What does the error look like?
Error [ERR_STREAM_WRITE_AFTER_END]: write after endcode: 'ERR_STREAM_WRITE_AFTER_END'The output file stops early and the process exits with ERR_STREAM_WRITE_AFTER_END
Cause 1 of 3
end() runs before the async writes are done
You seeThe writes happen inside forEach(async ...), .then() callbacks or event handlers, and end() sits right after them
Check
ERR_STREAM_WRITE_AFTER_END shows up here because end() ran while writes started inside forEach callbacks were still waiting. Array.prototype.forEach never waits for the promises its callback returns, so the end() after the loop closes the file early.
grep -nE "forEach\(async|\.end\(" src/export.jsFix
Use a plain for...of loop so each await finishes before the next row. When write() returns false, wait for the drain event, and call end() only after the loop.
import { createWriteStream } from 'node:fs';
import { once } from 'node:events';
const out = createWriteStream('report.csv');
for (const row of rows) {
const line = await formatRow(row);
if (!out.write(line + '\n')) await once(out, 'drain');
}
out.end();
await once(out, 'finish');Verify
Run the export and compare the number of lines in the file with the number of rows you passed in.
wc -l report.csvConfirmed by nodejs.org
Cause 2 of 3
pipe() ended the target when its source finished
You seeWrites made after src.pipe(out) fail once src has emitted end
Check
The write after end error comes from pipe() in this case: by default readable.pipe() calls end() on the destination as soon as the source ends. Code that pipes one file into a target and then writes a footer, or pipes a second file in, is writing to a closed stream.
grep -nE "\.pipe\(" src/*.jsFix
Pass { end: false } to each pipe() that must leave the target open, wait for that source to end, then close the target yourself.
import { createReadStream, createWriteStream } from 'node:fs';
import { once } from 'node:events';
const out = createWriteStream('bundle.txt');
for (const part of ['header.txt', 'body.txt']) {
const src = createReadStream(part);
src.pipe(out, { end: false });
await once(src, 'end');
}
out.end('-- end of bundle --\n');Verify
The bundle holds both parts plus the closing line, and nothing is printed to stderr.
tail -n 3 bundle.txtConfirmed by nodejs.org
Cause 3 of 3
A shared stream was ended by an earlier job
You seeThe first export, request or test passes; every later one in the same process fails at once
Check
Write after end hits every job after the first when they share one stream and the first job ended it. A stream opened at module load lives as long as the process, so log writableEnded at the start of each job to confirm.
console.log('stream already ended:', logStream.writableEnded);Fix
Open the file stream inside the job and close it when that job is done. If the stream really must be shared, such as an app log, keep it open for the life of the process and never end it from a job.
import { createWriteStream } from 'node:fs';
import { once } from 'node:events';
export async function exportJob(rows, file) {
const out = createWriteStream(file);
for (const row of rows) {
if (!out.write(JSON.stringify(row) + '\n')) await once(out, 'drain');
}
out.end();
await once(out, 'finish');
}Verify
Call the job twice in a row in one process; both output files are complete.
wc -l export-1.ndjson export-2.ndjsonConfirmed by nodejs.org
How do I stop it coming back?
- For file output, prefer pipeline() from node:stream/promises with an async generator as the source; it closes the file for you after the generator returns.
- Create one stream per export or job instead of reusing a module-level one.
- Keep an error listener on every stream you open. Without one, an error event ends the whole Node.js process.
- Do not mix forEach with async callbacks when the callback writes to a stream.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.