Node.js
/Advanced
Streams Module
Definition
A core module representing a sequence of data made available over time. Streams allow you to read or write massive amounts of data chunk-by-chunk without storing it all in memory.
Explain Like I'm New
Imagine watching a movie on Netflix. You don't download the entire 5GB video file to your hard drive before hitting 'Play'. You download a tiny 10-second 'chunk', watch it, throw it away, and download the next chunk. Streams allow Node to read a 10GB file using only 50MB of RAM by processing it in tiny chunks.
Real World Example
Uploading a 2GB video file to a Node server. If you use standard methods, Node tries to load all 2GB into RAM and crashes. With streams, it reads 64kb, saves it to disk, and repeats, keeping RAM usage near zero.
Common Use Cases
- •Processing large files
- •Video/Audio streaming
- •Handling massive network requests
Terminal Output
bash / terminal
const fs = require('fs');
// Instead of fs.readFile (which loads the whole file into memory),
// we create a stream that reads the file in tiny chunks.
// Note: This file doesn't actually exist in this sandbox
// const readStream = fs.createReadStream('./massive-video.mp4');
// const writeStream = fs.createWriteStream('./copy-video.mp4');
console.log("Simulating a stream...");
// Instead of real files, let's look at the standard process streams:
// process.stdout is a Writable Stream! It streams text to your terminal.
process.stdout.write("Hello ");
process.stdout.write("World!\n");
// How piping works:
// readStream.pipe(writeStream);
// This automatically manages backpressure, reading chunk 1 from A,
// writing chunk 1 to B, and repeating until finished.
Interview Questions
basic
- What is the main advantage of using streams?
intermediate
- What are the four types of streams in Node.js?
advanced
- What is backpressure in Node streams?