CodeBlanks Logo Icon CodeBlanks

pipe

Learn to connect streams with .pipe.

pipe

The pipe method connects a Readable to a Writable; data flows automatically. Signature: readable.pipe(writable). This way you do not write "data" and write calls by hand; pipe manages them all.

Example: source.pipe(target). Each chunk from the source is written to the target automatically; when the stream ends, the target's end() is called and the "finish" event fires. pipe also handles backpressure: if the target is slow, the source waits. This is the shortest way to move data from source to target safely.

Chaining with pipe

pipe returns the target Writable, so you can chain. This is especially powerful with Transform streams: source.pipe(transformer).pipe(target). Data is transformed first, then written to the target.

A simple chain: const source = Readable.from(["a", "b"]); const target = new Writable({ write(c, e, cb) { console.log("Pipe: " + c.toString()); cb(); } }); source.pipe(target);. You catch completion with target.on("finish", () => console.log("Pipe done")). Since pipe returns the target, source.pipe(target).on("finish", ...) also works; this keeps chains short.

Practice Connect two streams with pipe

Create source with Readable.from(["a", "b", "c"]). Create a Writable named target: inside write print "Pipe: " + chunk.toString() and call cb(). Connect with source.pipe(target). On target.on("finish", ...) print "Pipe done".

Starter code

index.js
// Import Readable and Writable
// write here

// Create source and target
// write here

// Connect source to target and listen for finish
// write here

Sample solution

index.js
const { Readable, Writable } = require("stream");
const source = Readable.from(["a", "b", "c"]);
const target = new Writable({
  write(chunk, enc, cb) { console.log("Pipe: " + chunk.toString()); cb(); }
});
source.pipe(target);
target.on("finish", () => console.log("Pipe done"));

Expected output

Pipe: a
Pipe: b
Pipe: c
Pipe bitti

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does kaynak.pipe(hedef) do?

index.js
kaynak.pipe(hedef)
  • Hedefi siler
  • Automatically writes chunks from the source to the destination Correct answer
  • Only returns the destination's name
  • Restarts the source

Explanation: pipe writes chunks to the target automatically.

2 Match each piece to its role

Term Meaning
pipe Connects streams
Readable Source stream
Writable Target stream
"finish" Target completed

3 Complete the pipe call

Question
kaynak.____(hedef);
Answer
kaynak.pipe(hedef);

Explanation: pipe connects source and target.

All lessons in Intermediate