Skip to content
jshacks.dev
APIs

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.

1 min read
Summarize in AI

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.

csv-export.jsJavaScript
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();
Text
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.

Also inAsync
Taggednode 24
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

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.