Stream CSV export from API
Stream a CSV export from an API with a generator and stream.pipeline, so a million rows never sit in memory together.
Building a whole CSV as one string needs memory for every row at once. A generator that yields a line at a time, piped to the response, uses the same memory for ten rows or ten million.
import { createServer } from 'node:http';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
const escape = (value) => `"${String(value).replaceAll('"', '""')}"`;
async function* rows() {
yield 'id,name\n';
for (const [id, name] of [[1, 'Ada'], [2, 'Grace "Amazing"']]) {
yield `${id},${escape(name)}\n`;
}
}
const server = createServer(async (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/csv',
'Content-Disposition': 'attachment; filename="users.csv"',
});
await pipeline(Readable.from(rows()), res);
});
await new Promise((resolve) => server.listen(0, resolve));
const res = await fetch(`http://localhost:${server.address().port}/`);
console.log(await res.text());
server.close();id,name
1,"Ada"
2,"Grace ""Amazing"""
Quotes inside a field are doubled and the field is wrapped in quotes, the rule from RFC 4180. pipeline also handles backpressure, pausing the generator when the client reads slowly, and destroys both sides if either fails.
In a real route, the generator reads from a database cursor, not a literal array. Once headers are sent, you cannot change the status code, so a failure half-way ends with a cut-off file; log it and consider a trailing marker. Prefix values that start with =, +, - or @ to avoid spreadsheet formula injection.