Sikau

Node.js · Day 3 · about 30 min

Reading and writing files

fs/promises, JSON and paths.

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!).

The rest of this lesson

  • Errors from the file systemexplain
  • Safer writesexplain
  • What's the error code?predict
  • Error codesmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 18 lessons of Node.js