The File System

`node:fs` — Read, Write, and Watch Files

The File System

The fs module is Node's bridge to the file system — read, write, list, watch, delete.

4 min read Level 1/5 #nodejs#fs#files
What you'll learn
  • Read and write files
  • List directory contents
  • Choose between sync, callback, and promise APIs

node:fs is the standard-library bridge to the file system. Reading, writing, listing, watching — all here.

Three Flavors

The same operation comes in three API styles:

StyleWhereExample
Promisenode:fs/promisesawait readFile(path)
Callbacknode:fsreadFile(path, (err, data) => ...)
Syncnode:fsreadFileSync(path)

For modern code: use the promise API.

Read a File

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

const text = await readFile("README.md", "utf8");
console.log(text);

The "utf8" encoding makes the result a string. Without it, you’d get a Buffer (raw bytes).

Write a File

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

await writeFile("out.txt", "hello\n", "utf8");

Overwrites if the file exists. Use appendFile to add to the end.

List a Directory

import { readdir } from "node:fs/promises";

const entries = await readdir(".");
console.log(entries);   // ['package.json', 'src', 'README.md']

For more info (file vs dir, hidden, etc.), pass { withFileTypes: true }:

const entries = await readdir(".", { withFileTypes: true });
for (const e of entries) {
  console.log(e.isDirectory() ? "dir " : "file", e.name);
}

File Info

import { stat } from "node:fs/promises";

const s = await stat("README.md");
console.log(s.size);      // bytes
console.log(s.mtime);     // last modified Date
console.log(s.isFile());  // true

Watching

import { watch } from "node:fs/promises";

const watcher = watch("src", { recursive: true });
for await (const event of watcher) {
  console.log(event.eventType, event.filename);
}

Async iterators over file changes — great for build tools.

Up Next

Sync vs async — when to use which.

Sync vs Async →