How do you read a file in Node.js?
1. Asynchronous reading (via a callback)
Load the built-in fs module:
javascript
import fs from 'fs';And read the file:
javascript
fs.readFile('./data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
console.log('File contents:', data);
});'utf8'gets you a string instead of aBuffer.- If the file isn't found, you get an
ENOENTerror. - This approach doesn't block the main thread (it's asynchronous).
2. Asynchronous reading with fs/promises (via async/await)
The modern, concise, and preferred option.
javascript
import { readFile } from 'fs/promises';
try {
const data = await readFile('./data.txt', 'utf8');
console.log('File contents:', data);
} catch (err) {
console.error('Error reading the file:', err);
}Advantages:
- No callbacks, plays nicely with
async/await; - The code reads "synchronously";
- A great fit for modern apps (Node 14+).
3. Synchronous reading (blocking)
Sometimes handy at initialization (for example, loading configuration):
javascript
import fs from 'fs';
try {
const data = fs.readFileSync('./config.json', 'utf8');
console.log('Configuration:', data);
} catch (err) {
console.error('Error:', err);
}But:
- It blocks code execution until the file is read;
- Not recommended on a server, only for CLI/initialization.
4. Streaming reads (for large files)
If a file is very large (gigabytes), streams are the better choice, they read the file in pieces instead of all at once into memory.
javascript
import fs from 'fs';
const stream = fs.createReadStream('./bigfile.txt', 'utf8');
stream.on('data', chunk => {
console.log('Got a chunk of data:', chunk);
});
stream.on('end', () => {
console.log('Reading finished!');
});
stream.on('error', err => {
console.error('Error:', err);
});Advantages:
- Doesn't load the whole file into memory;
- Data can be processed as it arrives;
- Ideal for logs, streaming, HTTP responses.
5. Comparing the approaches
| Approach | Method | Asynchronous | Use case |
|---|---|---|---|
| Callback | fs.readFile() | Yes | The basic, older style |
| Promise | fs/promises.readFile() | Yes | The modern standard |
| Synchronous | fs.readFileSync() | No | Short scripts only |
| Stream | fs.createReadStream() | Yes | Large files |
6. Example: reading a JSON file
javascript
import { readFile } from 'fs/promises';
try {
const raw = await readFile('./config.json', 'utf8');
const config = JSON.parse(raw);
console.log('Config:', config);
} catch (err) {
console.error('Error reading JSON:', err);
}Node.js doesn't parse JSON automatically, JSON.parse() needs to be called.
In one sentence
To read a file in Node.js, use
fs.readFile()(asynchronously),fs/promises.readFile()(viaawait), or thefs.createReadStream()stream for large files.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.