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

TypeDescriptionExample
ReadableStream you can read data fromfs.createReadStream()
WritableStream you can write data tofs.createWriteStream()
DuplexBoth readable and writableTCP sockets
TransformModify data while reading/writingzlib.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

EventDescription
dataTriggered when a chunk is available (Readable)
endTriggered when all data is read
errorTriggered when an error occurs
finishTriggered when writing is complete (Writable)
pipeTriggered when piping starts
unpipeTriggered 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...