Stream large responses instead of buffering
Pipe a large file or query result to the HTTP response with pipeline instead of reading it into memory first, keeping memory use flat in Node.js 24.
Reading a 500 MB file into a string before sending it needs 500 MB of memory per request. Streaming sends it in chunks, so memory use stays small.
import http from 'node:http';
import { createReadStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
http.createServer(async (req, res) => {
res.writeHead(200, { 'content-type': 'text/csv' });
try {
await pipeline(createReadStream('./exports/big.csv'), res);
} catch (error) {
console.log('stream ended early:', error.code);
}
}).listen(3000);$ curl -s localhost:3000 | head -c 20
id,name,email
1,Adapipeline connects the file stream to the response, handles backpressure so a slow client does not make the server buffer the rest, and destroys both streams when either fails. If the client disconnects halfway, the promise rejects, which is why it sits inside a try.
The buffered version, res.end(await readFile(path)), is simpler for small files, and unlike streaming it lets you set a content-length. When the data comes from a database, use a cursor or a streaming query so you do not load all rows first. Once you have written the headers you cannot send a different status after an error. See [stream.pipeline](https://nodejs.org/api/stream.html#streampipelinestreams-options).