Streams are a way to handle data piece by piece instead of loading everything into memory at once.
They are ideal for working with large files, network data, and real-time processing.
Traditional file handling:
Loads entire data into memory
Slower and memory-intensive
Stream-based handling:
Processes data in small chunks
Faster and memory-efficient
Supports real-time data flow
Node.js provides four main types of streams:
Used to read data.
Examples:
fs.createReadStream()
HTTP request stream
Used to write data.
Examples:
fs.createWriteStream()
HTTP response stream
Can read and write data.
Example:
TCP sockets
Modify data while streaming.
Example:
Compression
Encryption
Common events:
| Event | Description |
|---|---|
data | Data chunk received |
end | No more data |
error | Error occurred |
finish | Write completed |
pipe() connects streams together.
✔ Simplest way to transfer data
✔ Handles backpressure automatically
Backpressure occurs when:
Data is produced faster than it is consumed
Streams handle this automatically using pipe().
File uploads/downloads
Video streaming
Data compression
Reading large logs
Low memory usage
High performance
Scalable
Ideal for large data
| Streams | Buffers |
|---|---|
| Process data in chunks | Store entire data |
| Memory efficient | Memory heavy |
| Suitable for large data | Suitable for small data |
Use pipe() whenever possible
Handle error events
Close streams properly
Streams process data chunk-by-chunk
Node.js supports Readable, Writable, Duplex, and Transform streams
Streams improve performance and memory usage
Widely used in real-world Node.js applications
Take quizzes related to this topic and see where you stand!
Start Quiz Now