Thuta Learning
Node.js
IntermediateWeb DevelopmentBeginner

File System (fs)

Node.jsLesson 730 min

What you'll walk away with

  • Use readFile, writeFile, appendFile, readdir and rm with await
  • Explain why passing an encoding gives a string and omitting it gives a Buffer
  • Know that relative paths resolve against process.cwd() and build paths safely
  • Check err.code, handle only the errors you expect and rethrow the rest
  • Create a temporary folder with mkdtemp and clean it up in finally

Explain it simply

Explain it simply

The fs (file system) module is Node's hand on the disk. A file path works like a street address: with the right address you can deliver or collect a letter (data), and with a wrong one you get back "nobody lives here" (ENOENT).

With node:fs/promises you ask "please read this file" and get a Promise straight away. Your program can keep doing other work while the disk is busy, and await hands you the result when it arrives.

Problem → Why → Solution

The problem: trusting file code that destroys data

A small note-taking CLI works when you run it from the project folder. Run it from another folder and it cannot find notes.json, so all your notes seem to vanish. Worse, on the day notes.json has a stray comma, JSON.parse fails, the catch block assumes "no notes yet" and the whole file is overwritten with a single note. Hundreds of notes are gone.

notes-cli.mjs
import { readFileSync, writeFileSync } from "node:fs";

function loadNotes() {
  try {
    return JSON.parse(readFileSync("notes.json", "utf8")); // relative to cwd!
  } catch {
    return []; // missing file? no permission? broken JSON? all become "no notes"
  }
}

const notes = loadNotes();
notes.push("buy milk");
writeFileSync("notes.json", JSON.stringify(notes)); // a broken file is wiped

Why does this happen?

A relative path such as "notes.json" resolves against the terminal's current folder (process.cwd()), not the script's folder. fs errors carry a code such as ENOENT or EACCES, but the catch-all block never looks at it and treats every failure the same way, which is how the data gets destroyed.

Core concept: build the path, await the call, read the error code

Every function in node:fs/promises returns a Promise. readFile(path, "utf8") gives you the whole file as a string; without an encoding you get a Buffer of raw bytes, which is right for binary files such as images and PDFs. writeFile creates the file if it is missing and replaces its entire content if it exists, while appendFile adds to the end. With the { flag: "wx" } option, writeFile fails with EEXIST when the file already exists, which protects you from accidental overwrites.

Build paths with two rules. First, relative paths resolve against process.cwd(), so for a file next to your script build an absolute path such as join(import.meta.dirname, "notes.json"). Second, never glue path pieces together with +; use join() from node:path, which handles the separator difference between Windows and Linux.

Every fs error carries err.code, err.syscall and err.path. ENOENT means the file or folder does not exist, EEXIST means it already does, EACCES or EPERM means permission was denied, and EISDIR means a folder sits where a file was expected. Check only the codes you can handle and rethrow the rest with throw err. For experiments and tests, mkdtemp(join(tmpdir(), "prefix-")) creates a fresh, uniquely named folder inside the OS temp folder, and rm(dir, { recursive: true, force: true }) in a finally block cleans it up whether or not an error occurred.

FunctionWhat it does
readFile(path, "utf8")Reads the whole file as a string
writeFile(path, data)Creates the file or replaces all of it
appendFile(path, data)Adds to the end, creating the file if needed
mkdir(path, { recursive: true })Creates a folder and its parents; no error if it exists
readdir(path)Lists a folder's entry names as an array
rm(path, { recursive: true, force: true })Deletes a file or folder; no error if missing
Mental model: a safe file operation
  1. Build an absolute path with join()
  2. Await the fs/promises call
  3. Get data, or an error with a code
  4. Handle known codes, rethrow the rest

Not every error means "file missing"; always look at err.code.

General pattern: read, write, handle by code

javascript
import { readFile, writeFile } from "node:fs/promises";

try {
  const text = await readFile(filePath, "utf8");
  await writeFile(otherPath, newContent, "utf8");
} catch (err) {
  if (err.code === "EXPECTED_CODE") {
    // recover: use a default, create the file, show a clear message...
  } else {
    throw err; // anything else is a real problem
  }
}

Await the fs calls in order and catch errors in one place. Inside catch, check err.code, recover only from situations you understand and rethrow anything unexpected.

Example: a note file inside a temporary folder

This script creates a fresh folder with mkdtemp, writes note.txt, appends a line, reads it back and lists what the folder holds. It also tries to read a file that does not exist and shows the error code. Finally, the finally block deletes the whole folder, so nothing is left on your disk. Only file names are printed, never the full temp path, so the output is the same on every machine.

notes.mjs
// notes.mjs - reading and writing files with node:fs/promises
import { appendFile, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const dir = await mkdtemp(join(tmpdir(), "fs-demo-"));
try {
  const notePath = join(dir, "note.txt");
  await writeFile(notePath, "Node.js can write files!\n", "utf8");
  await appendFile(notePath, "It can append to them too.\n", "utf8");

  const text = await readFile(notePath, "utf8");
  console.log("File content:");
  console.log(text.trimEnd());
  console.log("Folder now holds:", await readdir(dir));

  try {
    await readFile(join(dir, "missing.txt"), "utf8");
  } catch (err) {
    console.log("Reading a missing file fails with", err.code);
  }
} finally {
  await rm(dir, { recursive: true, force: true });
}

Code breakdown

  1. Line 6const dir = await mkdtemp(join(tmpdir(), "fs-demo-"));

    tmpdir() is the OS temporary folder. mkdtemp adds six random characters after "fs-demo-" and creates the folder, so every run gets a new folder that never collides with other programs.

  2. Lines 9-10await appendFile(notePath, "It can append to them too.\n", "utf8");

    writeFile creates the file and appendFile adds to its end. Because of await, the append starts only after the write has finished, so the two lines are in the right order.

  3. Line 12const text = await readFile(notePath, "utf8");

    Passing "utf8" returns a string instead of a Buffer. text.trimEnd() removes the final newline before printing.

  4. Line 15console.log("Folder now holds:", await readdir(dir));

    readdir returns entry names, not full paths, so this output is identical on every machine.

  5. Lines 19-20console.log("Reading a missing file fails with", err.code);

    await turns the rejected Promise into a throw, so a normal try/catch catches it. err.code is "ENOENT"; check the code, never the message text.

  6. Lines 22-23await rm(dir, { recursive: true, force: true });

    finally runs whether or not the try block threw, so the temp folder is always removed. recursive deletes the contents too, and force avoids an error if the folder is already gone.

You should see
File content:
Node.js can write files!
It can append to them too.
Folder now holds: [ 'note.txt' ]
Reading a missing file fails with ENOENT

Safe writes: write a temp file, then rename

If the process crashes, or the power fails, in the middle of writeFile, the file can be left half-written. To avoid that, write the data to a temp file next to the target first, then swap it in with rename. On a single file system, rename replaces the file in one step (atomically on Linux and macOS), so readers see either the old version or the new one, never a torn file.

atomic-write.mjs
// atomic-write.mjs - never leave a half-written file behind
import { mkdtemp, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

async function writeFileAtomic(filePath, text) {
  const tempPath = `${filePath}.${process.pid}.tmp`;
  await writeFile(tempPath, text, "utf8");
  await rename(tempPath, filePath); // swap the finished file into place
}

const dir = await mkdtemp(join(tmpdir(), "atomic-"));
try {
  const file = join(dir, "data.json");
  await writeFileAtomic(file, JSON.stringify({ version: 1 }));
  await writeFileAtomic(file, JSON.stringify({ version: 2 }));
  console.log("Content:", await readFile(file, "utf8"));
  console.log("Files left:", await readdir(dir));
} finally {
  await rm(dir, { recursive: true, force: true });
}

In real projects

Where fs shows up in real projects

Reading configuration files and templates at startup, appending to log files, generating CSV reports and saving uploaded images to disk are everyday server tasks. Project generators such as create-vite, static site generators and build tools are, at heart, programs that create folders and read or write thousands of files with fs. Tests create their own sandbox folder with mkdtemp, so parallel test runs never trample each other's files.

Putting a user-supplied file name straight into a path is a security bug: a name such as "../../etc/passwd" can escape the intended folder (path traversal). Resolve the path and check that it still lies inside the base folder; the Path Module lesson covers this in detail. Apps running in containers often keep uploads in object storage such as S3, because files on a container's local disk can disappear when it restarts.

Common mistakes

Common mistakes

1. Assuming a relative path points next to the script

readFile("data.csv") searches from process.cwd(), so it works from the project root and fails with ENOENT from inside src/. For files next to the script, use join(import.meta.dirname, "data.csv").

2. Forgetting await

Calling readFile(path) right after writeFile(path, data); without await can read before the write has finished. A rejected Promise that nobody awaits also becomes an unhandled rejection, which crashes the Node process. Await (or return) every fs/promises call.

3. Treating every error as "file not found"

catch { return defaults; } also hides permission problems (EACCES), folders in the wrong place (EISDIR) and corrupt JSON (SyntaxError), and the next write may then destroy the data. Always include if (err.code !== "ENOENT") throw err;.

4. Checking existence before reading

Checking with access() and then calling readFile() leaves a gap in which another process can delete the file (a race condition), so the check proves nothing. Read directly and handle ENOENT.

Mini challenge

Mini challenge: load settings, create them when missing

Write loadSettings(filePath), which reads a JSON settings file. When the file is missing it creates one with default settings and returns them, but it must not hide other errors such as broken JSON. Test three situations inside a temporary folder.

  • Use node:fs/promises only
  • Handle ENOENT specifically and rethrow every other fs error
  • Write the default file with { flag: "wx" } so an existing file is never clobbered
  • Do not hide JSON parse errors; they must reach the caller
  • Return { settings, created } and delete the temp folder in finally
settings.mjs
// settings.mjs - load JSON settings, create defaults when the file is missing
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const DEFAULTS = { theme: "light", fontSize: 16 };

async function loadSettings(filePath) {
  // TODO: read the file as UTF-8
  // TODO: on ENOENT only: write DEFAULTS (flag "wx"), return { settings, created: true }
  // TODO: any other read error: rethrow
  // TODO: parse the JSON (let a SyntaxError escape), return { settings, created: false }
}

const dir = await mkdtemp(join(tmpdir(), "settings-"));
try {
  // TODO: 1st call -> file missing, 2nd call -> valid file, 3rd -> broken JSON
} finally {
  // TODO: remove dir
}

Expected: The output should be: 1st call created file: true { theme: 'light', fontSize: 16 } 2nd call created file: false { theme: 'dark', fontSize: 18 } Broken file: SyntaxError

Show hint

Put only readFile inside the try and keep JSON.parse outside it; then a parse error can never land in the ENOENT handler. Return a copy of the defaults with { ...DEFAULTS }, or a caller's change would modify DEFAULTS itself.

Show solution
settings.mjs
// settings.mjs - load JSON settings, create defaults when the file is missing
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const DEFAULTS = { theme: "light", fontSize: 16 };

async function loadSettings(filePath) {
  let text;
  try {
    text = await readFile(filePath, "utf8");
  } catch (err) {
    if (err.code !== "ENOENT") throw err; // EACCES, EISDIR... are real problems
    const json = JSON.stringify(DEFAULTS, null, 2) + "\n";
    await writeFile(filePath, json, { flag: "wx" });
    return { settings: { ...DEFAULTS }, created: true };
  }
  return { settings: JSON.parse(text), created: false }; // bad JSON throws
}

const dir = await mkdtemp(join(tmpdir(), "settings-"));
try {
  const file = join(dir, "settings.json");
  const first = await loadSettings(file);
  console.log("1st call created file:", first.created, first.settings);

  await writeFile(file, JSON.stringify({ theme: "dark", fontSize: 18 }));
  const second = await loadSettings(file);
  console.log("2nd call created file:", second.created, second.settings);

  await writeFile(file, "{ theme: dark }");
  await loadSettings(file).catch((err) => console.log("Broken file:", err.name));
} finally {
  await rm(dir, { recursive: true, force: true });
}

Quick quiz 1 / 3

What does await readFile("photo.png") return when no encoding is given?

Quick quiz 2 / 3

settings.json already exists. What does await writeFile("settings.json", data, { flag: "wx" }) do?

Quick quiz 3 / 3

/app/src/report.mjs calls readFile("data.csv"). You run node src/report.mjs from /app. Which file does Node open?

What to remember

  • Every node:fs/promises function returns a Promise; await the calls in order.
  • "utf8" gives a string, no encoding gives a Buffer, and writeFile replaces the whole file.
  • Relative paths resolve against process.cwd(); build absolute ones with join(import.meta.dirname, ...).
  • Check err.code (ENOENT, EEXIST, EACCES), handle what you understand and rethrow the rest.
  • Run experiments inside an mkdtemp folder and clean it up with rm in finally.

File system — Node.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

File System (fs) | Thuta Learning