Programs that remember
Browsers can't freely touch your disk; Node can. Reading config, saving data as JSON, writing logs — it all starts with the built-in fs module.
fs/promises and path
import { readFile, writeFile, mkdir } from "node:fs/promises";
import path from "node:path";
const file = path.join("data", "orders.json");
const orders = JSON.parse(await readFile(file, "utf8"));
orders.push({ id: orders.length + 1, dish: "Momo", qty: 2 });
await mkdir("backup", { recursive: true });
await writeFile(file, JSON.stringify(orders, null, 2));
await writeFile(path.join("backup", "orders.json"), JSON.stringify(orders));
console.log("Saved", orders.length, "orders");
console.log(await readFile(file, "utf8"));- Missing file? readFile rejects with an error whose code is "ENOENT" — catch it and use a default.
- Relative paths resolve from the folder you started Node in (process.cwd()); in ES modules use import.meta.dirname for the file's own folder.
- Writing JSON files is fine for small tools; real apps use a database (later courses!).