Node.js Backend Development Bootcamp · 课时

背压、pipe() 与 pipeline() 工具

诊断内存膨胀,并使用 pipeline() 安全连接流、传递错误和遵循背压。

第 3 / 4 课13 个步骤

背压、pipe() 与 pipeline() 工具 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Memory Bloats in Streams

A Node.js Readable stream can produce data faster than a Writable can consume it. If you never tell the producer to slow down, unconsumed chunks pile up in an internal buffer and your process memory grows until the GC can't keep up.

  • A slow disk, slow network socket, or slow database write is the typical consumer.
  • A fast file read or HTTP upload is the typical producer.

The mechanism that makes the producer wait for the consumer is called backpressure. Misusing streams almost always means backpressure was ignored.

The Naive (Broken) Copy

Here is the classic memory bug. We listen for data and call dst.write() for every chunk, ignoring its return value.

If dst is slower than src, the unwritten chunks queue up inside dst's buffer with no upper bound. For a multi-gigabyte file this can exhaust RAM.

const fs = require('fs');

const src = fs.createReadStream('big.bin');
const dst = fs.createWriteStream('copy.bin');

// BUG: return value of write() is ignored, so backpressure is never honored
src.on('data', (chunk) => {
  dst.write(chunk);
});
src.on('end', () => dst.end());

What write() Actually Returns

writable.write(chunk) returns a boolean:

  • true — the internal buffer is below highWaterMark; keep writing.
  • false — the buffer is full; you should stop writing and wait for the 'drain' event before sending more.

Honoring this return value is the manual way to apply backpressure. The producer must pause until the consumer signals it has drained.

Manual Backpressure with pause/resume

Done by hand, backpressure means: when write() returns false, pause() the source; when the destination emits 'drain', resume() it.

This works but is verbose and easy to get wrong — you also have to wire up error and end handling for both streams.

const fs = require('fs');

const src = fs.createReadStream('big.bin');
const dst = fs.createWriteStream('copy.bin');

src.on('data', (chunk) => {
  const ok = dst.write(chunk);
  if (!ok) {
    src.pause();              // stop reading until the buffer drains
    dst.once('drain', () => src.resume());
  }
});
src.on('end', () => dst.end());

pipe() Does This For You

readable.pipe(writable) wires up the same pause/resume/drain dance automatically and honors backpressure out of the box.

It returns the destination stream, so you can chain through transforms:

  • src.pipe(gzip).pipe(dst)

For most simple copies, pipe() is far better than the manual loop above.

const fs = require('fs');
const zlib = require('zlib');

const src = fs.createReadStream('big.bin');
const gzip = zlib.createGzip();
const dst = fs.createWriteStream('big.bin.gz');

// pipe() handles backpressure across all three streams
src.pipe(gzip).pipe(dst);

The Hidden Flaw in pipe()

pipe() handles backpressure, but it does not forward errors. If gzip or dst emits 'error', the source is not destroyed automatically.

  • The upstream stream keeps its file descriptor open — a resource leak.
  • An unhandled 'error' event throws and can crash the process.

To use pipe() safely you must attach an error handler to every stream and manually destroy the others. That boilerplate is exactly what pipeline() removes.

Enter stream.pipeline()

stream.pipeline() connects a series of streams, propagates backpressure, forwards errors, and destroys every stream in the chain when any of them fails or finishes.

It takes the streams in order followed by a callback that fires once with an error (or null on success):

const { pipeline } = require('stream');
const fs = require('fs');
const zlib = require('zlib');

pipeline(
  fs.createReadStream('big.bin'),
  zlib.createGzip(),
  fs.createWriteStream('big.bin.gz'),
  (err) => {
    if (err) {
      console.error('Pipeline failed:', err.message);
    } else {
      console.log('Pipeline succeeded');
    }
  }
);

The Promise-Based pipeline()

In modern code use the promise version from stream/promises. It resolves on success and rejects on failure, so a single try/catch covers the whole chain and cleanup.

This is the recommended way to wire streams in async backend handlers.

const { pipeline } = require('stream/promises');
const fs = require('fs');
const zlib = require('zlib');

async function compress() {
  try {
    await pipeline(
      fs.createReadStream('big.bin'),
      zlib.createGzip(),
      fs.createWriteStream('big.bin.gz')
    );
    console.log('done');
  } catch (err) {
    console.error('failed:', err.message);
  }
}

compress();

A Runnable In-Memory Pipeline

You don't need files to see pipeline() work. Readable.from() turns any iterable into a stream, and a Transform can uppercase each chunk. The whole thing runs standalone.

Notice how errors from any stage would reject the awaited pipeline().

const { Readable, Transform } = require('stream');
const { pipeline } = require('stream/promises');

const source = Readable.from(['hello ', 'stream ', 'world']);

const upper = new Transform({
  transform(chunk, _enc, cb) {
    cb(null, chunk.toString().toUpperCase());
  }
});

const chunks = [];
const sink = new Transform({
  transform(chunk, _enc, cb) {
    chunks.push(chunk.toString());
    cb();
  }
});

(async () => {
  await pipeline(source, upper, sink);
  console.log(chunks.join(''));
})();

highWaterMark: Tuning the Buffer

Each stream has a highWaterMark (default 16 KB for byte streams, 16 objects for object-mode). It is the threshold at which write() returns false and reads pause.

  • A larger highWaterMark increases throughput but uses more memory per stream.
  • A smaller one applies backpressure sooner, capping memory more tightly.

It is a buffering threshold, not a hard limit — but it is the lever that controls how aggressively backpressure kicks in.

const fs = require('fs');

// Pause reads after only 64 KB is buffered downstream
const src = fs.createReadStream('big.bin', { highWaterMark: 64 * 1024 });
const dst = fs.createWriteStream('copy.bin', { highWaterMark: 64 * 1024 });

src.pipe(dst);

pipeline() in an HTTP Handler

A common backend mistake is buffering an entire upload or download into memory before responding. Streaming the response body with pipeline() keeps memory flat and tears everything down if the client disconnects.

Because the HTTP response is a Writable, backpressure from a slow client automatically throttles the file read.

const http = require('http');
const fs = require('fs');
const { pipeline } = require('stream');

http.createServer((req, res) => {
  pipeline(
    fs.createReadStream('big.bin'),
    res,
    (err) => {
      if (err) {
        console.error('stream error:', err.message);
        res.destroy();
      }
    }
  );
}).listen(3000);

Quick Check

You are streaming a file to a slow client through a gzip transform. Which approach safely honors backpressure AND cleans up every stream if the client disconnects mid-transfer?

Recap

Key takeaways for wiring streams safely:

  • Backpressure stops a fast producer from overwhelming a slow consumer; ignoring write()'s boolean return is the root cause of stream memory bloat.
  • pipe() handles backpressure but not error forwarding or cleanup — a leaked-FD trap.
  • stream.pipeline() (callback or the stream/promises version) propagates backpressure, forwards errors, and destroys all streams in the chain.
  • highWaterMark tunes how soon backpressure engages, trading memory for throughput.
  • In HTTP handlers, stream with pipeline() instead of buffering full payloads.
免费开始

用 AI 导师学习 JavaScript — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
22
课程
92

常见问题解答

「背压、pipe() 与 pipeline() 工具」课时是免费的吗?

是的 — 「背压、pipe() 与 pipeline() 工具」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

「背压、pipe() 与 pipeline() 工具」这节课中我会学到什么?

诊断内存膨胀,并使用 pipeline() 安全连接流、传递错误和遵循背压。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Node.js Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「背压、pipe() 与 pipeline() 工具」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 可读、可写、双工与转换流内部机制
  2. 使用 _transform 和 _flush 实现自定义转换流
  3. 背压、pipe() 与 pipeline() 工具
  4. 异步迭代器与通过 for-await-of 遍历流
← 返回 Node.js Backend Development Bootcamp