All academies

File System (fs)

Read, write, append, and delete files — sync, callback, and promise APIs.

20 minLevel 8 of 20

Three flavors of the same module

The fs module exposes every operation in three styles:

  • Synchronous — fs.readFileSync(): blocks until done, returns the result directly. Simple, but freezes the event loop.
  • Callback — fs.readFile(path, cb): the original async style; the callback receives (err, data).
  • Promise-based — fs.promises.readFile() (or require("fs/promises")): returns a promise, plays perfectly with async/await. This is the style to prefer in modern code.

Rule of thumb: promises for servers and apps, sync versions acceptable in short scripts and startup code.

One read, three ways
const fs = require("fs");

fs.writeFileSync("/tmp/demo.txt", "hello fs");

// 1. Synchronous - blocks:
const sync = fs.readFileSync("/tmp/demo.txt", "utf8");
console.log("sync:", sync);

// 2. Callback - error-first:
fs.readFile("/tmp/demo.txt", "utf8", (err, data) => {
  if (err) return console.error(err);
  console.log("callback:", data);
});

// 3. Promises - the modern default:
fs.promises.readFile("/tmp/demo.txt", "utf8")
  .then((data) => console.log("promise:", data));

Reading and writing files

readFile slurps a whole file into memory; writeFile replaces a file's contents (creating it if needed); appendFile adds to the end without erasing.

Always pass an encoding like "utf8" when working with text — without it, readFile returns a raw Buffer of bytes instead of a string. For huge files, reading everything into memory is wasteful; that's what streams are for (a later lesson).

Write, append, read with async/await
const fs = require("fs/promises");

async function main() {
  await fs.writeFile("/tmp/notes.txt", "First line\n");
  await fs.appendFile("/tmp/notes.txt", "Second line\n");

  const text = await fs.readFile("/tmp/notes.txt", "utf8");
  console.log(text);

  // Without an encoding you get a Buffer:
  const bytes = await fs.readFile("/tmp/notes.txt");
  console.log("Is Buffer?", Buffer.isBuffer(bytes), "-", bytes.length, "bytes");
}

main().catch(console.error);

Directories and file metadata

Beyond file contents, fs manages the file tree itself:

  • mkdir(path, { recursive: true }) — create a directory (and any missing parents)
  • readdir(path) — list a directory's entries
  • stat(path) — metadata: size, timestamps, and type checks like isDirectory()
  • rename(oldPath, newPath) — move or rename
  • rm(path, { recursive: true }) — delete files or whole directory trees

readdir with { withFileTypes: true } returns Dirent objects so you can tell files from folders without extra stat calls.

Building and exploring a directory tree
const fs = require("fs/promises");

async function main() {
  await fs.mkdir("/tmp/project/src", { recursive: true });
  await fs.writeFile("/tmp/project/src/app.js", "console.log('hi')");
  await fs.writeFile("/tmp/project/README.md", "# Project");

  const entries = await fs.readdir("/tmp/project", { withFileTypes: true });
  for (const entry of entries) {
    console.log(entry.isDirectory() ? "[dir] " : "[file]", entry.name);
  }

  const info = await fs.stat("/tmp/project/README.md");
  console.log("README size:", info.size, "bytes");
}

main().catch(console.error);

Checking existence and handling errors

File operations fail all the time — missing files, permission problems, disks filling up. Node errors carry a code property that tells you what went wrong:

  • ENOENT — no such file or directory
  • EACCES / EPERM — permission denied
  • EEXIST — already exists
  • EISDIR — expected a file, found a directory

Avoid the check-then-act pattern (if exists, then read) — the file can vanish between the two steps. Instead, just attempt the operation and handle the error.

Attempt and handle, don't check first
const fs = require("fs/promises");

async function readIfPresent(path) {
  try {
    return await fs.readFile(path, "utf8");
  } catch (err) {
    if (err.code === "ENOENT") return null; // fine: file absent
    throw err; // anything else is a real problem
  }
}

async function main() {
  console.log("missing file:", await readIfPresent("/tmp/nope.txt"));

  await fs.writeFile("/tmp/yes.txt", "found me");
  console.log("existing file:", await readIfPresent("/tmp/yes.txt"));
}

main().catch(console.error);

Deleting and a word on paths

fs.rm removes files; add { recursive: true, force: true } to delete directories and ignore already-missing targets. There is also fs.unlink, the older file-only deletion API.

When building paths for fs calls, never concatenate strings with + and / — separators differ across operating systems. Use path.join (next lesson) and anchor application files on __dirname, not the working directory.

Clean removal
const fs = require("fs/promises");

async function main() {
  await fs.mkdir("/tmp/scratch/deep", { recursive: true });
  await fs.writeFile("/tmp/scratch/deep/file.txt", "temp");

  // Remove a whole tree; force ignores missing paths:
  await fs.rm("/tmp/scratch", { recursive: true, force: true });

  try {
    await fs.stat("/tmp/scratch");
  } catch (err) {
    console.log("Gone - error code:", err.code); // ENOENT
  }
}

main().catch(console.error);

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

Which fs style should modern application code prefer?