CodeBlanks Logo Icon CodeBlanks

Readable stream

Learn to read data with a Readable stream.

Readable stream

A Readable stream flows data from a source to the program. Readable.from(array) creates a readable stream from an array. Data arrives piece by piece through the "data" event; when the stream ends, the "end" event fires.

Example: const r = Readable.from(["apple", "pear"]); r.on("data", (chunk) => console.log("Read: " + chunk)); r.on("end", () => console.log("Done"));. Here the "data" listener is called once per chunk; chunk is the current piece. The "end" listener fires after all chunks flow. Since Readable extends EventEmitter, you listen with on.

Capturing data

When you add a "data" listener on a Readable, the stream enters flowing mode and chunks arrive automatically. The chunk is usually a Buffer or string; chunk.toString() converts it to a string.

To collect chunks you can push them into an array: const chunks = []; r.on("data", (c) => chunks.push(c));. Then in the "end" event you join and process them. Readable.from yields array items as-is, so chunk.toString() works safely. When the stream ends, "end" fires reliably, regardless of how many chunks arrived.

Practice Read chunks from a Readable

Create a readable stream named r with Readable.from(["apple", "pear"]). Listen for the "data" event: for each chunk print "Read: " + chunk. Listen for the "end" event: print "Done".

Starter code

index.js
// Import Readable and create an r instance
// write here

// Listen for the "data" event
// write here

// Listen for the "end" event
// write here

Sample solution

index.js
const { Readable } = require("stream");
const r = Readable.from(["apple", "pear"]);
r.on("data", (chunk) => console.log("Read: " + chunk));
r.on("end", () => console.log("Done"));

Expected output

Okundu: elma
Okundu: armut
Bitti

Questions and answers

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

1 Match each event to its meaning

Term Meaning
"data" Fires for each chunk
"end" Fires when the stream ends
chunk The current piece
Readable.from Creates a readable stream

2 Complete the data listener

Question
r.on("____", (chunk) => console.log("Okundu: " + chunk));
Answer
r.on("data", (chunk) => console.log("Okundu: " + chunk));

Explanation: The data event fires for each chunk.

3 How many times does Readable.from(["a", "b"]) emit data?

index.js
r.on("data", fn)
  • Never emits
  • Only once
  • Sonsuza kadar
  • Twice, once for each string item Correct answer

Explanation: Two items in the array means two chunks.

All lessons in Intermediate