Node.js
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.
Exercise 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".
Show example solution
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"));
Test yourself
-
What does kaynak.pipe(hedef) do?
kaynak.pipe(hedef)
- Hedefi siler
- Automatically writes chunks from the source to the destination
- Only returns the destination's name
- Restarts the source
Show answer
Automatically writes chunks from the source to the destination — pipe writes chunks to the target automatically.
-
Match each piece to its role
- pipe
- Connects streams
- Readable
- Source stream
- Writable
- Target stream
- "finish"
- Target completed
-
Complete the pipe call
kaynak.____(hedef);
Show answer
kaynak.pipe(hedef);
Next lesson: Transform stream