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.
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.
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')));"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.