What are streams?
- Node.js course
- Intermediate
- Lesson 7/116
- 5 min
Learn the stream concept and its types.
What are streams?
A stream is a data structure that processes data piece by piece. Instead of loading all data into memory at once, it flows in small slices called chunks. This saves memory with large files or continuous data.
In Node.js streams come from the stream module. For example Readable.from(["a", "b"]) creates a readable stream from an array. Streams appear in http requests, fs file reading and process.stdout. Streaming data is the standard way to process large data from disk or network piece by piece.
Stream types
Node.js has four core stream types. Readable flows in the reading direction (source → program). Writable flows in the writing direction (program → target). Duplex both reads and writes (two-way). Transform reads, transforms the data and writes.
All are imported from the stream module: const { Readable, Writable, Transform } = require("stream");. Readable.from(array) is the simplest way to create a readable stream; it turns an array into a list of chunks. We will examine each type in the following lessons.
Practice Create a Readable
Import Readable from the stream module. Create a readable stream named stream with Readable.from(["data"]). Print "Stream ready" with console.log.
Starter code
// Import Readable from the stream module
// write here
// Create a stream with Readable.from
// write here
// Print the ready message
// write hereSample solution
const { Readable } = require("stream");
const stream = Readable.from(["data"]);
console.log("Stream ready");Expected output
Stream hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the main benefit of using streams?
Readable.from([...])- Makes the code shorter
- Catches errors automatically
- Processes large data chunk by chunk and saves memory Correct answer
- Carries only numbers, not text
Explanation: Streams process data in chunks to save memory.
2 Complete the module name
const { Readable } = require("____");
const { Readable } = require("stream");
Explanation: The built-in module for streams is stream.
3 Match each type to its direction
| Term | Meaning |
|---|---|
Readable |
Reads from a source |
Writable |
Writes to a target |
Transform |
Transforms then writes |
Duplex |
Flows both ways |