CodeBlanks Logo Icon CodeBlanks

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.

Practice 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().

Starter code

index.js
// Import fs/promises
// Define async function run
// Write with writeFile, read with readFile, log with console.log
// Call run

Sample solution

index.js
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();

Expected output

hello world

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.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: readFile

Question
const data = await fs.____('notes.txt', 'utf8');
console.log(data);
Answer
const data = await fs.readFile('notes.txt', 'utf8');
console.log(data);

Explanation: You read the file with readFile.

2 What does the 'utf8' argument do in fs.readFile?

  • It compresses the file
  • It makes the result return as a string Correct answer
  • It locks the file
  • It makes the call synchronous

Explanation: The utf8 argument returns the result as a string.

3 readFile concepts

Term Meaning
readFile reads a file
utf8 returns as string
ENOENT file not found

All lessons in Beginner