Middle+
Have you ever worked with streams in Node.js?
sobes.tech AI
Answer from AI
Yes, in Node.js, streams are used for efficient handling of data flows, for example, when reading and writing files, working with HTTP requests and responses. They allow processing data in chunks without loading the entire content into memory.
Example of reading a file using a stream:
const fs = require('fs');
const readStream = fs.createReadStream('file.txt', { encoding: 'utf8' });
readStream.on('data', chunk => {
console.log('Received data chunk:', chunk);
});
readStream.on('end', () => {
console.log('File reading completed');
});
readStream.on('error', err => {
console.error('Error reading file:', err);
});
Streams come in different types: Readable, Writable, Duplex, and Transform, which allow flexible construction of data processing pipelines.