Middle+
What types of streams are there in Node.js?
sobes.tech AI
Answer from AI
In Node.js, there are four main types of streams that implement the EventEmitter interface and allow working with data streams:
- Readable — streams from which data can be read (e.g., reading a file, HTTP request).
- Writable — streams to which data can be written (e.g., writing to a file, sending an HTTP response).
- Duplex — streams that are both readable and writable (e.g., TCP sockets).
- Transform — a special type of duplex stream that can modify or transform data as it passes through (e.g., compression, encryption).
Example of using readable and writable streams:
const fs = require('fs');
const readable = fs.createReadStream('input.txt');
const writable = fs.createWriteStream('output.txt');
// Copy file contents
readable.pipe(writable);
Thus, streams enable efficient handling of large amounts of data without loading all information into memory at once.