Skip to main content
Albero Academy

Core Modules & the File System

Node's built-in modules — reading and writing files, working with paths, and the async patterns that define Node.

Chapter 2Node.js15 min readBeginner friendly
  • #Node.js
  • #fs
  • #Async

Node ships with a standard library of core modules — no install needed. The most-used is fs (file system). This chapter covers reading and writing files and, crucially, the three generations of async style you'll encounter.

Core modules

  • fs — read/write files & directories
  • path — build file paths that work on every OS
  • http — create servers and make requests
  • os, crypto, events, url — system info, hashing, event emitters, URL parsing

Reading & writing files

The modern approach uses the promise-based API with async/await:

fs with promises
import { readFile, writeFile } from "fs/promises";
async function run() {
await writeFile("notes.txt", "Hello Albero\n");
const text = await readFile("notes.txt", "utf-8");
console.log(text);
// JSON round-trip
const data = { name: "Aanya", score: 92 };
await writeFile("data.json", JSON.stringify(data, null, 2));
const loaded = JSON.parse(await readFile("data.json", "utf-8"));
}
run();

Callbacks, promises, async

Node's I/O comes in three async styles. You'll read all three; write the third:

StyleLooks like
Callbacks (old)fs.readFile(path, cb)
PromisesreadFile(path).then(…)
async/await (modern)await readFile(path)

Paths

Never build paths by gluing strings with "/" — that breaks on Windows. Use the path module:

cross-platform paths
import path from "path";
path.join("data", "users", "list.json"); // data/users/list.json (or \ on Windows)
path.extname("report.csv"); // ".csv"
path.basename("/a/b/report.csv"); // "report.csv"

Practice

Write a script that reads a JSON file of students, adds a new student, and writes it back — all with fs/promises and async/await, wrapped in try/catch. Build every path with path.join.

Key takeaways

  1. 01Core modules (fs, path, http, os, crypto…) are built in — no install required.
  2. 02Use fs/promises with async/await; pass "utf-8" to get strings, not Buffers.
  3. 03Wrap file operations in try/catch — missing files and permissions throw.
  4. 04Node I/O comes in callback, promise and async/await styles — prefer async/await.
  5. 05Build paths with path.join for cross-platform correctness.