Skip to content
jshacks.dev
Node.js

Write CSV rows with a stream

Write CSV rows to a file stream in Node.js 24, quote fields that hold commas or quotes per RFC 4180, and wait for drain so memory stays flat.

2 min read
Summarize in AI

Exporting a million database rows to CSV should write as it goes. Two details decide whether the file is correct and whether memory stays flat: quoting, and respecting backpressure.

export.mjsJavaScript
import { createWriteStream } from 'node:fs';
import { once } from 'node:events';
import { readFile } from 'node:fs/promises';

const field = (v) => {
  const s = String(v ?? '');
  return /[",\r\n]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
};

const out = createWriteStream('users.csv');
const rows = [
  ['id', 'name', 'note'],
  [1, 'Ada', 'likes "engines"'],
  [2, 'Linus, T.', null],
];

for (const row of rows) {
  if (!out.write(row.map(field).join(',') + '\r\n')) await once(out, 'drain');
}
out.end();
await once(out, 'finish');
console.log(JSON.stringify(await readFile('users.csv', 'utf8')));
Text
"id,name,note\r\n1,Ada,\"likes \"\"engines\"\"\"\r\n2,\"Linus, T.\",\r\n"

field quotes a value only when it contains a comma, a double quote or a line break, and doubles any quote inside it, which is the escaping RFC 4180 defines; a null becomes an empty field. write returns false once the stream's buffer is full, and waiting for drain before the next row is what keeps a large export from buffering everything in memory. See RFC 4180.

Line endings are CRLF because that is what the RFC and Excel expect. Excel also wants a UTF-8 byte order mark at the start to read accents correctly, which you can write once before the header. Values that start with =, +, - or @ are run as formulas by spreadsheet apps, so exports of user input should prefix them with a single quote.

Also inAsync
Taggednode 24
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.