Junior — Middle
What types of data streams are implemented in Node.js?
sobes.tech AI
Answer from AI
In Node.js, four main types of data streams are implemented:
- Readable streams — allow reading data in parts, for example, reading a file or data from a network.
- Writable streams — allow writing data in parts, for example, writing to a file or sending data over a network.
- Duplex streams — combine the capabilities of reading and writing, for example, network sockets.
- Transform streams — are duplex streams that can modify data during transmission, such as compression or encryption.
Example of using a readable stream to read a file:
const fs = require('fs');
const readable = fs.createReadStream('file.txt', { encoding: 'utf8' });
readable.on('data', chunk => {
console.log('Received data chunk:', chunk);
});
readable.on('end', () => {
console.log('File reading completed');
});