In Node.js, Streams are an abstract interface for handling operations such as reading/writing files and network communication, primarily used for processing large volumes of data or real-time data processing.
Node.js provides four basic stream types:
-
Readable Streams - These streams are used for reading data from a data source. For example, reading data from a file or from an HTTP response. A common example is using the
fs.createReadStream()method to read data from the file system. -
Writable Streams - These streams are used for writing data to a destination. For example, writing data to a file or sending data to an HTTP request. Using the
fs.createWriteStream()method to write data to a file is a common use case. -
Duplex Streams - Streams that can perform both read and write operations simultaneously. They operate independently on each channel, enabling concurrent reading and writing. An example is network sockets, which can both receive and send data on the same connection.
-
Transform Streams - A special type of Duplex Stream where the output is a transformation of the input. This means the data is processed after writing and before it can be read from the stream. Typical applications include data compression and encryption. For example, using
zlib.createGzip()to create a compression stream that compresses the data before output.
Each stream is an instance of EventEmitter, capable of emitting events. For example, readable streams emit data and end events, while writable streams emit finish and error events. By leveraging these features, Node.js can efficiently handle large volumes of data while maintaining low memory usage.