How do you read a large file efficiently in Node.js to avoid memory issues?

Question

Grade: Education Subject: Support
How do you read a large file efficiently in Node.js to avoid memory issues?
Asked by:
75 Viewed 75 Answers

Answer (75)

Best Answer
(318)
For large files, use streams (`fs.createReadStream`). Streams read the file in chunks, preventing the entire file from being loaded into memory at once. This is much more memory-efficient. Example: `const stream = fs.createReadStream('largefile.txt'); stream.on('data', (chunk) => { console.log(chunk.toString()); });`