Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Node.js, PHP and APIs

Writing to a file stream throws 'write after end' in Node.js

Your error

Error [ERR_STREAM_WRITE_AFTER_END]: write after end2 more lines it can show

Fix it fast

Most common cause, 1 of 3

end() runs before the async writes are done

Use a plain for...of loop so each await finishes before the next row.

Fix
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');
Did this fix it?
Full steps for this cause: check, fix, verify

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.

  • Applies to Node.js 22, Node.js 24, Node.js 26
  • Updated
  • By Maaz Zindani, Senior Software Engineer

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.

Run this first
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:

  1. 1end() runs before the async writes are doneThe writes happen inside forEach(async ...), .then() callbacks or event handlers, and end() sits right after them
  2. 2pipe() ended the target when its source finishedWrites made after src.pipe(out) fail once src has emitted end
  3. 3A shared stream was ended by an earlier jobThe 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 end
  • code: '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.

Check
grep -nE "forEach\(async|\.end\(" src/export.js

Fix

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.

Fix
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.

Verify
wc -l report.csv

Confirmed by nodejs.org

Did this fix it?

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.

Check
grep -nE "\.pipe\(" src/*.js

Fix

Pass { end: false } to each pipe() that must leave the target open, wait for that source to end, then close the target yourself.

Fix
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.

Verify
tail -n 3 bundle.txt

Confirmed by nodejs.org

Did this fix it?

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.

Check
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.

Fix
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.

Verify
wc -l export-1.ndjson export-2.ndjson

Confirmed by nodejs.org

Did this fix it?

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.

Which stack is behind this page?

Projects of mine on the same stack: TaxiDex, Workforce.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.