Skip to content
jshacks.dev
Performance

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.

1 min read
Summarize in AI

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.

server.jsJavaScript
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);
Text
$ curl -s localhost:3000 | head -c 20
id,name,email
1,Ada

pipeline 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).

Also inAsync
Taggednode 24
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

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.