agyanadda@gmail.com

Node.js File System (fs)

Node.js Core Modules 1 min read Updated Dec 3, 2026 Topic 6 of 30

The fs (file system) module reads, writes and manages files and folders.

Three styles

  1. Promises (recommended): import { readFile } from 'node:fs/promises' with await
  2. Callbacks: fs.readFile(path, cb)
  3. Sync: fs.readFileSync(path) — blocks everything; fine for small scripts, avoid in servers

Common functions

  • readFile(path, 'utf8') — read text
  • writeFile(path, data) — create or replace
  • appendFile(path, data) — add to the end
  • mkdir(path, { recursive: true }) — create folders
  • readdir(path) — list a folder
  • stat(path) — size, dates, isFile()
  • rename(old, new), unlink(path) (delete file), rm(path, { recursive: true })

JSON files

JSON.parse(await readFile('data.json', 'utf8')) and writeFile('data.json', JSON.stringify(obj, null, 2)).

Errors

Wrap in try/catch. A missing file gives error code ENOENT.

Example

Example — A simple JSON notes store JavaScript
import { readFile, writeFile, mkdir } from 'node:fs/promises';

const FILE = 'data/notes.json';

async function loadNotes() {
  try {
    return JSON.parse(await readFile(FILE, 'utf8'));
  } catch (err) {
    if (err.code === 'ENOENT') return [];   // file does not exist yet
    throw err;
  }
}

async function addNote(text) {
  const notes = await loadNotes();
  notes.push({ id: notes.length + 1, text, createdAt: new Date().toISOString() });
  await mkdir('data', { recursive: true });
  await writeFile(FILE, JSON.stringify(notes, null, 2));
  return notes;
}

const notes = await addNote('Learn the fs module');
console.log(`You have ${notes.length} note(s)`);

The first run creates data/notes.json and prints "You have 1 note(s)". Each run adds another note to the file.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which import gives the promise-based fs functions?

Exercise 2 True / False

readFileSync is the best choice inside a busy web server.

Exercise 3 Fill in the Blank

A missing file gives the error code ___

Frequently Asked Questions

Do not load it all with readFile. Use a stream (fs.createReadStream) or the readline module to process it piece by piece, so memory stays low.