Node.js Streams

🌊 Node.js – Streams

Streams are objects in Node.js that allow reading or writing data in chunks, instead of loading the entire data into memory.
This is memory-efficient and suitable for large files.

Streams are event-based and work with EventEmitter.


✅ 1. Types of Streams

Type Description Example
Readable Stream you can read data from fs.createReadStream()
Writable Stream you can write data to fs.createWriteStream()
Duplex Both readable and writable TCP sockets
Transform Modify data while reading/writing zlib.createGzip()

✅ 2. Readable Streams

Used to read data in chunks.


 


✅ 3. Writable Streams

Used to write data in chunks.


 


✅ 4. Pipe Streams

You can pipe data from a readable stream to a writable stream easily.


 

✅ Automatically handles data events and writes data efficiently.


✅ 5. Transform Streams

Used to modify data while reading/writing.

Example: Convert text to uppercase.


 


✅ 6. Duplex Streams

Both readable and writable.

Example: TCP socket (simplified):


 


✅ 7. Event Listeners in Streams

Event Description
data Triggered when a chunk is available (Readable)
end Triggered when all data is read
error Triggered when an error occurs
finish Triggered when writing is complete (Writable)
pipe Triggered when piping starts
unpipe Triggered when piping stops

✅ 8. Example: Read + Transform + Write Stream


 


🎯 Advantages of Streams

  • Efficient memory usage

  • Handle large files without crashing

  • Supports piping & chaining

  • Real-time processing of data

  • Works well with network operations

You may also like...