CodeBlanks Logo Icon CodeBlanks

Summary - Streams

Combine Readable, Writable and pipe to write a file copy.

Summary - Streams

In this group you learned the core tools of streams: reading data with Readable, writing data with Writable, connecting streams with pipe and transforming data with Transform.

Now you will combine them into a file copy simulation. You will connect a source Readable to a target Writable with pipe; each chunk is copied and a message is printed when the flow completes. This mini task shows how data flows from source to target.

Copy design

The copy skeleton: a source Readable, a target Writable and a pipe connection. Each chunk from the source is written to the target; when the flow ends, the "finish" event fires.

Flow: const source = Readable.from(["line1", "line2"]); const target = new Writable({ write(chunk, enc, cb) { console.log("Copied: " + chunk.toString()); cb(); } }); source.pipe(target); target.on("finish", () => console.log("Copy done"));. Output: Copied: line1, Copied: line2, Copy done. Since pipe moves chunks automatically, you do not call write by hand.

Practice Write a file copy

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

Starter code

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

// Create source and target
// write here

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

Sample solution

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

Expected output

Kopyalandı: satır1
Kopyalandı: satır2
Kopyalama tamam

Questions and answers

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

1 What pieces does the copy simulation combine?

index.js
kaynak.pipe(hedef)
  • Only new Writable
  • Only console.log
  • Only require
  • Readable, Writable ve pipe Correct answer

Explanation: Readable as source, Writable as target and pipe connects.

2 Match each tool to its role

Term Meaning
Readable.from Creates the source stream
new Writable Creates the target stream
pipe Connects source to target
"finish" Copy complete

All lessons in Intermediate