Node.js › File System & File Processing
What is the difference between fs.readFile() and fs.createReadStream() for reading a file in Node.js?
BeginnerAnswer
fs.readFile() reads an entire file into memory at once before invoking its callback with the complete contents -- simple, but problematic for large files since the whole file must fit in memory simultaneously. fs.createReadStream() reads the file incrementally in configurable chunks, emitting 'data' events as each chunk becomes available, using a bounded, predictable amount of memory regardless of the file's total size, making it the appropriate choice for processing large files.
// Loads the entire file into memory
fs.readFile('huge-file.csv', 'utf-8', (err, data) => { /* entire file in `data` */ });
// Processes incrementally, bounded memory usage
fs.createReadStream('huge-file.csv').on('data', (chunk) => { /* process one chunk at a time */ });Real-world example A log-analysis tool processing multi-gigabyte log files switches from fs.readFile() (which was crashing with an out-of-memory error) to fs.createReadStream(), processing the file line by line with bounded memory regardless of the file's total size.