Junior — Middle
How to distinguish the use of readFile and readStream methods in the context of their operation and data processing approaches?
sobes.tech AI
Answer from AI
The readFile method reads the entire file at once and returns its contents after fully loading it into memory. This is convenient for small files when you need to get the data immediately.
The readStream method creates a read stream that allows processing data in parts (chunks) as they arrive. This is more efficient for large files, as it does not require loading the entire file into memory and allows starting data processing earlier.
Example of using readStream in Node.js:
const fs = require('fs');
const stream = fs.createReadStream('file.txt', 'utf8');
stream.on('data', chunk => {
console.log('Received data chunk:', chunk);
});
stream.on('end', () => {
console.log('File reading completed');
});