What is a Stream in Node.js?
1. Definition
A stream in Node.js is a way to handle reading or writing data in small chunks instead of loading the entire data into memory at once. It is useful for handling large files efficiently.
2. Types of Streams
- Readable: Read data (e.g., fs.createReadStream)
- Writable: Write data (e.g., fs.createWriteStream)
- Duplex: Read and write (e.g., sockets)
- Transform: Modify data while streaming
3. Why Use Streams
- Handles large data efficiently
- Reduces memory usage
- Faster processing
- Improves performance
4. Example
const fs = require("fs");
const readStream = fs.createReadStream("largeFile.txt", "utf8");
readStream.on("data", (chunk) => {
console.log("Chunk:", chunk);
});5. How Streams Work
- Data is processed in chunks
- Each chunk is handled as it arrives
- No need to load full file into memory
6. Advantages
- Efficient for large files
- Low memory usage
- Better performance
- Supports real-time data processing