Imagine you have a 5 GB video file.
If you try to read the entire file into memory at once, your application will consume a huge amount of RAM.
This can:
- Slow down your application
- Increase memory usage
- Even crash your server
Instead, Node.js reads the file in small chunks.
These chunks are called Streams.
Streams are one of the most powerful features of Node.js and are widely used for:
- Reading large files
- Writing large files
- Uploading images
- Downloading videos
- HTTP requests and responses
- File compression
- Real-time data processing
In this article, we'll learn everything about the Stream module with practical examples.
Let's get started!
What is a Stream?
A Stream is a way to process data piece by piece (chunk by chunk) instead of loading everything into memory at once.
Think of it like drinking water.
Without Streams
Water Tank
↓
Pour Everything Into One Huge Bucket
↓
Drink
With Streams
Water Tank
↓
Glass 1
↓
Glass 2
↓
Glass 3
↓
Drink While Receiving More Water
Node.js follows the second approach.
Why Do We Need Streams?
Imagine reading a 10 GB file.
Without Streams
Read Entire File
↓
Store in Memory
↓
Process File
Huge memory usage.
With Streams
Read Small Chunk
↓
Process Chunk
↓
Read Next Chunk
↓
Process Next Chunk
Very efficient.
Advantages of Streams
Streams provide several benefits:
- Lower memory usage
- Faster processing
- Better performance
- Suitable for large files
- Real-time data processing
- Efficient network communication
Types of Streams
Node.js provides four types of streams.
Stream TypePurposeReadableRead dataWritableWrite dataDuplexRead and WriteTransformRead, Transform, and Write
Let's understand each one.
Readable Streams
A Readable Stream is used to read data.
Examples:
- Reading files
- Reading HTTP requests
- Reading database exports
Create a Readable Stream
Suppose we have:
hello.txt
Content:
Welcome to Node.js Streams.
Create:
app.js
const fs = require("fs");
const readStream = fs.createReadStream("hello.txt");
readStream.on("data", (chunk) => {
console.log(chunk);
});
Run:
node app.js
Output:
<Buffer 57 65 6c 63 6f ...>
Why a Buffer?
Because streams read binary data.
Convert Buffer to String
const fs = require("fs");
const readStream = fs.createReadStream("hello.txt");
readStream.on("data", (chunk) => {
console.log(chunk.toString());
});
Output:
Welcome to Node.js Streams.
Read Stream Events
Readable streams emit several events.
data is Fired when data is available
end is Fired when reading finishes
error is Fired when an error occurs
close is Fired when the stream closes
Example:
const fs = require("fs");
const readStream = fs.createReadStream("hello.txt");
readStream.on("data", (chunk) => {
console.log(chunk.toString());
});
readStream.on("end", () => {
console.log("Reading Completed");
});
Output:
Welcome to Node.js Streams.
Reading Completed
Writable Streams
Writable streams are used to write data.
Examples:
- Saving files
- Writing logs
- Writing HTTP responses
Create a Writable Stream
const fs = require("fs");
const writeStream = fs.createWriteStream("output.txt");
writeStream.write("Hello");
writeStream.write("\nWelcome");
writeStream.write("\nNode.js");
writeStream.end();
Generated file:
Hello
Welcome
Node.js
Writable Stream Events
const fs = require("fs");
const writeStream = fs.createWriteStream("output.txt");
writeStream.write("Learning Streams");
writeStream.end();
writeStream.on("finish", () => {
console.log("Writing Completed");
});
Output:
Writing Completed
Pipe()
One of the biggest advantages of Streams is pipe().
Instead of manually reading and writing data:
Read
↓
Write
↓
Read
↓
Write
Node.js can do it automatically.
Copy a File Using Pipe
const fs = require("fs");
const readStream = fs.createReadStream("hello.txt");
const writeStream = fs.createWriteStream("copy.txt");
readStream.pipe(writeStream);
Output:
copy.txt
contains exactly the same data as:
hello.txt
How Pipe Works
Readable Stream
↓
pipe()
↓
Writable Stream
Node.js transfers data chunk by chunk.
Duplex Streams
A Duplex Stream can both:
- Read
- Write
Examples:
- TCP sockets
- WebSockets
- Network connections
Read
↓
Duplex
↓
Write
One object performs both operations.
Transform Streams
A Transform Stream is a special type of Duplex stream.
It:
- Reads data
- Modifies the data
- Writes the modified data
Examples:
- Compression
- Encryption
- Decryption
- File conversion
Create a Transform Stream
const { Transform } = require("stream");
const upperCase = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().toUpperCase());
},
});
upperCase.on("data", (chunk) => {
console.log(chunk.toString());
});
upperCase.write("hello");
upperCase.end();
Output:
HELLO
Reading Large Files Efficiently
Instead of:
const fs = require("fs");
const data = fs.readFileSync("large-video.mp4");
Use:
const fs = require("fs");
const stream = fs.createReadStream("large-video.mp4");
stream.on("data", (chunk) => {
console.log(chunk.length);
});
The file is processed chunk by chunk.
Memory usage stays low.
Understanding HighWaterMark
Streams read data in chunks.
The chunk size is controlled by highWaterMark.
Example:
const fs = require("fs");
const stream = fs.createReadStream("hello.txt", {
highWaterMark: 10,
});
stream.on("data", (chunk) => {
console.log(chunk.toString());
});
Here, Node.js reads 10 bytes at a time.
Without specifying highWaterMark, Node.js uses a default value (for file streams, it's typically 64 KB).
Error Handling
Always handle stream errors.
const fs = require("fs");
const stream = fs.createReadStream("unknown.txt");
stream.on("error", (error) => {
console.log(error.message);
});
Output:
ENOENT: no such file or directory
Build a File Copy Application
const fs = require("fs");
const readStream = fs.createReadStream("hello.txt");
const writeStream = fs.createWriteStream("backup.txt");
readStream.pipe(writeStream);
writeStream.on("finish", () => {
console.log("File Copied Successfully");
});
Output:
File Copied Successfully
Build a Logger
const fs = require("fs");
const logger = fs.createWriteStream("logs.txt", {
flags: "a",
});
logger.write("Application Started\n");
logger.write("User Logged In\n");
logger.end();
Generated file:
Application Started
User Logged In
Using flags: "a" appends data instead of overwriting the file.
Real-World Use Cases
Streams are used in:
- File uploads
- Video streaming platforms
- Audio streaming
- HTTP request/response handling
- Cloud storage
- Compression tools
- Image processing
- Logging systems
- Data migration
If you've ever watched a YouTube video before it finished downloading, you've experienced streaming in action.
Stream Methods
createReadStream() - Creates a readable stream
createWriteStream() - Creates a writable stream
pipe() - Connects two streams
write() - Writes data
end() - Ends a writable stream
pause() - Pauses reading
resume() - Resumes reading
Common Stream Events
data - Data is available
end - Reading completed
finish - Writing completed
error - Error occurred
close - Stream closed
Best Practices
When working with Streams:
- Use streams for large files instead of
readFile(). - Always handle the
errorevent. - Use
pipe()whenever possible instead of manually copying chunks. - Close writable streams using
end(). - Use Transform streams for modifying data while streaming.
- Adjust
highWaterMarkonly when you have a specific performance requirement and have measured its impact.
Common Beginner Mistakes
Here are some common mistakes developers make:
- Using
readFileSync()for very large files. - Forgetting to call
end()on writable streams. - Not handling stream errors.
- Reading an entire file into memory when a stream would be more efficient.
- Assuming streams always return strings instead of Buffers.
Final Thoughts
The Stream module is one of the most powerful features of Node.js. It enables applications to process large amounts of data efficiently without consuming excessive memory.
In this article, you learned:
- What Streams are
- Why Streams are important
- The four types of Streams
- How to create Readable and Writable streams
- How
pipe()works - What Duplex and Transform streams are
- How to handle stream events
- How to process large files efficiently
- Best practices for using Streams
As you continue learning Node.js, you'll find Streams at the heart of many real-world applications, including file uploads, HTTP servers, cloud storage integrations, media streaming, and data processing pipelines. Mastering Streams is an important step toward building scalable and high-performance Node.js applications.
Happy Coding! 🚀