Node.js
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.
Exercise 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".
Show example solution
const { Readable } = require("stream");
const r = Readable.from(["apple", "pear"]);
r.on("data", (chunk) => console.log("Read: " + chunk));
r.on("end", () => console.log("Done"));
Test yourself
-
Match each event to its meaning
- "data"
- Fires for each chunk
- "end"
- Fires when the stream ends
- chunk
- The current piece
- Readable.from
- Creates a readable stream
-
Complete the data listener
r.on("____", (chunk) => console.log("Okundu: " + chunk));
Show answer
r.on("data", (chunk) => console.log("Okundu: " + chunk));
-
How many times does Readable.from(["a", "b"]) emit data?
r.on("data", fn)
- Never emits
- Only once
- Sonsuza kadar
- Twice, once for each string item
Show answer
Twice, once for each string item — Two items in the array means two chunks.
Next lesson: Writable stream