What are streams in Node.js?

Answer

Streams are Node.js's way of handling reading and writing data sequentially, piece by piece, rather than loading everything into memory at once. This is essential for large files, real-time data, and network communication. There are four types: (1) Readable — source of data (fs.createReadStream, http.IncomingMessage); (2) Writable — destination for data (fs.createWriteStream, http.ServerResponse); (3) Duplex — both readable and writable (TCP sockets); (4) Transform — duplex stream that transforms data as it passes through (zlib for compression, crypto for encryption). Streams emit events: "data", "end", "error", "finish". The key method is readable.pipe(writable), which automatically manages data flow and backpressure. Example: fs.createReadStream("large.csv").pipe(transform).pipe(fs.createWriteStream("out.csv")) processes the file without loading it all into memory.