TExcelTAD
Home › Node.js › Node.js File System

Node.js File System

The node:fs module lets your program create, read, update and delete files and folders. Modern code uses its promise API, node:fs/promises, together with async/await. All the examples here run in an empty folder and clean up after themselves.

js
import { readFile, writeFile } from "node:fs/promises";   // ES module
const fs = require("node:fs/promises");                    // CommonJS

Writing and reading a text file

node · try it yourself
import { writeFile, readFile, appendFile, rm } from "node:fs/promises";

await writeFile("notes.txt", "Buy milk\n", "utf8");     // create or overwrite
await appendFile("notes.txt", "Call Sam\n");            // add to the end

const text = await readFile("notes.txt", "utf8");
console.log(text);
console.log("lines:", text.trim().split("\n"));

await rm("notes.txt");
Buy milk
Call Sam

lines: [ 'Buy milk', 'Call Sam' ]

Tip: Always pass an encoding ("utf8") when you want text. Without it, readFile returns a Buffer of raw bytes.

Common operations

Function (fs/promises) What it does
readFile(path, "utf8") read a whole file
writeFile(path, data) create or replace a file
appendFile(path, data) add to the end, creating it if needed
mkdir(path, { recursive: true }) create a folder (and parents)
readdir(path) list a folder's entries
stat(path) size, type, timestamps
rename(old, new) rename or move
copyFile(src, dest) copy a file
cp(src, dest, { recursive: true }) copy a whole folder
rm(path, { recursive: true, force: true }) delete a file or folder
access(path) check that a path exists / is accessible

Folders, listing and file info

node · try it yourself
import { mkdir, writeFile, readdir, stat, rename, rm } from "node:fs/promises";

await mkdir("project/src", { recursive: true });
await writeFile("project/README.md", "# Demo\n");
await writeFile("project/src/app.js", "console.log('hi');\n");

const entries = (await readdir("project", { withFileTypes: true }))
  .sort((a, b) => a.name.localeCompare(b.name));
for (const e of entries) {
  console.log(e.isDirectory() ? "[dir] " : "[file]", e.name);
}

await rename("project/README.md", "project/INFO.md");
console.log((await readdir("project")).sort());

const info = await stat("project/src/app.js");
console.log("app.js size:", info.size, "bytes, is file:", info.isFile());

console.log("recursive:", (await readdir("project", { recursive: true })).sort());
await rm("project", { recursive: true });
[file] README.md
[dir]  src
[ 'INFO.md', 'src' ]
app.js size: 19 bytes, is file: true
recursive: [ 'INFO.md', 'src', 'src/app.js' ]

Handling errors

File operations fail for many reasons: the file doesn't exist, you lack permission, the disk is full. A failed await throws an error with a code property you can check:

err.code Meaning
ENOENT no such file or directory
EEXIST file already exists
EACCES / EPERM permission denied
EISDIR expected a file but found a folder
ENOTEMPTY folder is not empty
node · try it yourself
import { readFile, writeFile, rm } from "node:fs/promises";

async function loadSettings(file) {
  try {
    return JSON.parse(await readFile(file, "utf8"));
  } catch (err) {
    if (err.code === "ENOENT") {
      console.log(`${file} not found, using defaults`);
      return { theme: "light" };
    }
    throw err; // something unexpected: let it bubble up
  }
}

console.log(await loadSettings("settings.json"));

await writeFile("settings.json", JSON.stringify({ theme: "dark" }));
console.log(await loadSettings("settings.json"));

await writeFile("settings.json", "{ broken json");
try {
  await loadSettings("settings.json");
} catch (err) {
  console.log("unexpected:", err.name);
}
await rm("settings.json");
settings.json not found, using defaults
{ theme: 'light' }
{ theme: 'dark' }
unexpected: SyntaxError

Note: Avoid checking whether a file exists before opening it ("check, then use"). Another process could delete it in between. Just try the operation and handle ENOENT.

Synchronous and callback versions

The original node:fs module offers the same functions in a blocking ...Sync form and a callback form. Sync is fine in small scripts and at startup; avoid it inside servers.

node · try it yourself
const fs = require("node:fs");

fs.writeFileSync("data.json", JSON.stringify({ visits: 1 }));

const data = JSON.parse(fs.readFileSync("data.json", "utf8"));
data.visits += 1;
fs.writeFileSync("data.json", JSON.stringify(data, null, 2));

console.log(fs.readFileSync("data.json", "utf8"));
console.log("exists:", fs.existsSync("data.json"));
fs.unlinkSync("data.json");
console.log("exists after unlink:", fs.existsSync("data.json"));
{
  "visits": 2
}
exists: true
exists after unlink: false

Big files

readFile loads the entire file into memory. For logs or uploads that may be gigabytes large, use streams (fs.createReadStream) to process the data chunk by chunk — covered in the Streams lesson. Use fs.watch to react when a file changes.

Test yourself

What does readFile('a.txt') return when you omit the encoding?

  1. A string
  2. A Buffer
  3. An array of lines
  4. undefined

Which error code means the file or folder does not exist?

  1. EEXIST
  2. EACCES
  3. ENOENT
  4. EISDIR

How do you create a/b/c when a doesn't exist yet?

  1. mkdir('a/b/c')
  2. mkdir('a/b/c', { recursive: true })
  3. writeFile('a/b/c')
  4. Three separate rm calls