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 & directoriespath— build file paths that work on every OShttp— create servers and make requestsos,crypto,events,url— system info, hashing, event emitters, URL parsing
Reading & writing files
The modern approach uses the promise-based API with async/await:
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-tripconst 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:
| Style | Looks like |
|---|---|
| Callbacks (old) | fs.readFile(path, cb) |
| Promises | readFile(path).then(…) |
| async/await (modern) | await readFile(path) |
Paths
Never build paths by gluing strings with "/" — that breaks on Windows. Use the path module:
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
- 01Core modules (fs, path, http, os, crypto…) are built in — no install required.
- 02Use fs/promises with async/await; pass "utf-8" to get strings, not Buffers.
- 03Wrap file operations in try/catch — missing files and permissions throw.
- 04Node I/O comes in callback, promise and async/await styles — prefer async/await.
- 05Build paths with path.join for cross-platform correctness.
