0Pricing
Node.js Backend Development Bootcamp · 강의

백프레셔, pipe() 및 pipeline() 유틸리티

메모리 증가를 진단하고 pipeline()으로 스트림을 안전하게 연결해 오류를 전달하고 백프레셔를 준수합니다.

백프레셔, pipe() 및 pipeline() 유틸리티은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.

자주 묻는 질문

“백프레셔, pipe() 및 pipeline() 유틸리티” 강의는 무료인가요?

네 — “백프레셔, pipe() 및 pipeline() 유틸리티” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“백프레셔, pipe() 및 pipeline() 유틸리티”에서 뭘 배우나요?

메모리 증가를 진단하고 pipeline()으로 스트림을 안전하게 연결해 오류를 전달하고 백프레셔를 준수합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“백프레셔, 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(으)로 돌아가기