Node.js
readFile
Learn to read files with fs.readFile.
Read with readFile
fs.readFile reads a file asynchronously and returns a Promise. If you pass 'utf8' as the second argument the result comes back as a string; without it you get a Buffer.
import fs from 'fs/promises';
const data = await fs.readFile('notes.txt', 'utf8');
console.log(data);
Here readFile loads the entire file into memory; it suits small and medium files. For very large files createReadStream reduces memory use. If the file is missing the Promise rejects with an ENOENT error.
Exercise Your turn: read content with readFile
Start with import fs from 'fs/promises'. Define an async function run(). First write with await fs.writeFile('notes.txt', 'hello world'). Then read with const data = await fs.readFile('notes.txt', 'utf8') and log with console.log(data). Call run().
Show example solution
import fs from 'fs/promises';
async function run() {
await fs.writeFile('notes.txt', 'hello world');
const data = await fs.readFile('notes.txt', 'utf8');
console.log(data);
}
run();
Error handling
If the file is missing, fs.readFile returns a rejected Promise and throws an ENOENT error. You can catch it with try/catch, so a missing file leads to an alternative path.
try {
const data = await fs.readFile('missing.txt', 'utf8');
} catch (err) {
console.error('file missing');
}
This is a common pattern in file work. If err.code is 'ENOENT' the file was not found; another code means a different problem. Catching errors keeps the application running instead of crashing.
Test yourself
-
Fill in the blank: readFile
const data = await fs.____('notes.txt', 'utf8');
console.log(data);
Show answer
const data = await fs.readFile('notes.txt', 'utf8');
console.log(data);
-
What does the 'utf8' argument do in fs.readFile?
- It compresses the file
- It makes the result return as a string
- It locks the file
- It makes the call synchronous
Show answer
It makes the result return as a string — The utf8 argument returns the result as a string.
-
readFile concepts
- readFile
- reads a file
- utf8
- returns as string
- ENOENT
- file not found
Next lesson: writeFile