Concept Explanation
Imagine you want to move 10,000 gallons of water from a lake to a house.
- The Buffer Way: You try to put all 10,000 gallons into a giant bucket and carry it. The bucket is too heavy (you run out of RAM) and you crash.
- The Stream Way: You lay a pipe. The water flows through the pipe in tiny pieces. You never have to hold all the water at once.
In Node, Streams allow you to process 10GB files even if your computer only has 2GB of memory.
Syntax or Core Structure
import { createReadStream, createWriteStream } from 'node:fs';
const reader = createReadStream('large_video.mp4');
const writer = createWriteStream('copy_video.mp4');
// The pipe() command handles everything!
reader.pipe(writer);
reader.on('end', () => console.log("Finished moving data!"));
Buffers: The Chunks in the Pipe
A Buffer is the small bucket of raw bytes that flows through the pipe at each moment. Streams hand you data one Buffer at a time — a fixed-length chunk of binary data you can decode with .toString():
reader.on('data', (chunk) => {
// chunk is a Buffer — a slice of the file
console.log("Got", chunk.length, "bytes");
console.log(chunk.toString()); // decode to text
});
Common Mistakes
- Buffering a Huge File:
fs.readFileloads the entire file into RAM. For big files, always stream instead. - Ignoring Backpressure: If the writer is slower than the reader, data piles up.
.pipe()handles this for you; manual.on('data')does not. - Forgetting Errors: Streams emit
'error'events — an unhandled one crashes the whole process.
Best Practices
- Prefer pipe(): It manages flow, backpressure, and cleanup automatically.
- Handle Every Event: Wire up
'error'on both the reader and the writer. - Use pipeline(): Node's
stream.pipeline()chains streams together and forwards errors cleanly.
Practice Exercises
- The Stream Machine: Create a ReadStream for a text file and log how many "chunks" of data Node receives.
- The Transformer: Research
Transformstreams and explain how you could use one to turn all text to UPPERCASE while it's being streamed. - Pipe Power: Explain why
.pipe()is better than manually listening to.on('data')(Hint: research "Backpressure").