---
title: "How do I use streams in Node.js, and why use pipeline()?"
description: "Streams process data in chunks so large files never sit in memory at once. Connect them with pipeline() from node:stream/promises, which handles errors, cleanup and backpressure for you."
url: https://www.danny.engineering/answer/nodejs/how-do-i-use-streams-in-nodejs-and-why-use-pipeline
author: Danny
published: 2026-12-04T00:00:00.000Z
updated: 2026-11-28T00:09:00.000Z
tags: ["Node.js"]
---

# How do I use streams in Node.js, and why use pipeline()?

## The short answer


A stream moves data through your program in small chunks instead of loading it all at once. To connect streams, use `pipeline()` from `node:stream/promises`. It passes data from one stream to the next, slows the source down when the destination is busy, and destroys every stream if any of them fails.


```javascript
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";
import { pipeline } from "node:stream/promises";

await pipeline(
  createReadStream("access.log"),
  createGzip(),
  createWriteStream("access.log.gz"),
);

console.log("Compressed");
```


## Why it happens


Reading a file with `readFile` puts the whole thing in memory. That is fine for a config file, but a 4 GB log or a large upload can exhaust the heap or block the process for a long time. Streams solve this by handling one chunk (usually 64 KB for files) at a time.


Node has four kinds of stream:

- **Readable**: a source, such as `fs.createReadStream` or an incoming HTTP request.
- **Writable**: a destination, such as `fs.createWriteStream` or an HTTP response.
- **Duplex**: both at once, such as a TCP socket.
- **Transform**: a duplex that changes data as it passes through, such as `zlib.createGzip`.

The older way to connect them is `.pipe()`. It handles backpressure, but it does not forward errors. If the destination fails, the source keeps its file handle open, and an error on any stream without its own listener can crash the process. `pipeline()` was added to fix exactly that.


## How to fix it


### Use pipeline with async/await


The promise version is the most convenient. Wrap it in `try` and `catch` to handle failures from any stage.


```javascript
import { pipeline } from "node:stream/promises";
import { createReadStream, createWriteStream } from "node:fs";

try {
  await pipeline(createReadStream("in.csv"), createWriteStream("out.csv"));
} catch (error) {
  console.error("Copy failed:", error);
}
```


If one stream errors, `pipeline` destroys the others, so file descriptors and sockets are released.


### Transform data with an async generator


You do not need to subclass `Transform`. A `pipeline` stage can be an async generator function that receives the previous stream as an async iterable.


```javascript
import { pipeline } from "node:stream/promises";
import { createReadStream, createWriteStream } from "node:fs";

await pipeline(
  createReadStream("names.txt", { encoding: "utf8" }),
  async function* (source) {
    for await (const chunk of source) {
      yield chunk.toUpperCase();
    }
  },
  createWriteStream("names-upper.txt"),
);
```


Chunks are not lines. If you need to work line by line, use `node:readline` with `createInterface` on the read stream.


### Stream a file in an HTTP response


Sending a large file without streaming buffers it all first. With `pipeline`, the response is written as the file is read, and a client that disconnects early stops the read.


```javascript
import { createServer } from "node:http";
import { createReadStream } from "node:fs";
import { pipeline } from "node:stream/promises";

createServer(async (req, res) => {
  res.setHeader("Content-Type", "video/mp4");
  try {
    await pipeline(createReadStream("intro.mp4"), res);
  } catch (error) {
    if (error.code !== "ERR_STREAM_PREMATURE_CLOSE") console.error(error);
  }
}).listen(3000);
```


### Read a stream with for await


When you only want to consume data, readable streams are async iterables.


```javascript
import { createReadStream } from "node:fs";

let bytes = 0;
for await (const chunk of createReadStream("big.bin")) {
  bytes += chunk.length;
}
console.log(bytes);
```


### Cancel a pipeline


Pass an `AbortSignal` as the last argument to stop it, for example after a timeout.


```javascript
await pipeline(source, destination, { signal: AbortSignal.timeout(10_000) });
```


## Common pitfalls

- **Using .pipe() without error handling.** Prefer `pipeline()` everywhere. If you must use `.pipe()`, add an `error` listener to every stream.
- **Ignoring backpressure in manual writes.** If you call `write()` yourself, check its return value and wait for the `drain` event when it returns `false`. `pipeline` does this for you.
- **Collecting chunks into an array.** Pushing every chunk into memory defeats the point. Process each chunk and move on.
- **Mixing up the two imports.** `pipeline` from `node:stream` takes a callback; the one from `node:stream/promises` returns a promise.
- **Splitting multi-byte characters.** Set `encoding: "utf8"` on the read stream so characters are not cut in half between chunks.

## Related reading

- [Node.js: Stream API](https://nodejs.org/api/stream.html)
- [Node.js: Backpressuring in streams](https://nodejs.org/en/learn/modules/backpressuring-in-streams)
