Node.js theorytheory 0/50 · 0%
I/O · easy

9. The fs module

Reading and writing files, sync vs async vs promises.

`fs` reads and writes the filesystem in three flavours: synchronous (`readFileSync`, blocks the event loop), callback-based (`readFile(path, cb)`), and promise-based via `fs/promises`.

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

const config = JSON.parse(await readFile("./config.json", "utf8"));
await writeFile("./out.json", JSON.stringify({ ok: true }, null, 2));

Prefer the async APIs on servers: a synchronous read blocks every other request being handled on that same event loop. Sync APIs are fine for one-off scripts and startup-time config loading, where blocking briefly at boot is harmless.

Check your understanding

  1. 1. Why avoid `fs.readFileSync` inside a request handler on a server?

  2. 2. Which module exposes promise-based file APIs?

  3. 3. When is a synchronous fs call usually acceptable?