fs.readFile vs fs.createReadStream in Node.js

When working with the file system in Node.js, choosing the right method to read files is crucial for application performance and scalability. This article explains the key differences between fs.readFile and fs.createReadStream, detailing how they handle memory, process data, and when you should use each approach in your applications.

How They Work

The fundamental difference between these two methods lies in how they load file data into your computer’s memory.

fs.readFile (Buffer-based)

fs.readFile reads the entire contents of a file into memory asynchronously. Node.js allocates a single buffer large enough to hold the whole file. Once the entire file is successfully read and loaded into memory, the callback function is triggered, or the promise resolves with the complete file contents.

const fs = require('fs');

fs.readFile('large-file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data); // The entire file content is in memory here
});

fs.createReadStream (Stream-based)

fs.createReadStream reads the file in small, sequential chunks (by default, 64KB per chunk). Instead of waiting for the entire file to be read, it returns a Readable Stream object. This stream emits events (data, end, error) as chunks of data become available, allowing you to process data sequentially as it arrives.

const fs = require('fs');

const stream = fs.createReadStream('large-file.txt', { encoding: 'utf8' });

stream.on('data', (chunk) => {
  console.log('Received chunk of data:', chunk); // Processing data chunk-by-chunk
});

stream.on('end', () => {
  console.log('Finished reading file.');
});

Key Differences

1. Memory Consumption

2. Processing Speed and Latency

3. Maximum File Size Limits

When to Use Which?

Use fs.readFile when:

Use fs.createReadStream when: