Lesson 10 / 28
The fs Module
Reading and writing files, synchronously or asynchronously.
Reading a file
The async, Promise-based API lives under fs/promises.
import { readFile } from "node:fs/promises";
const text = await readFile("notes.txt", "utf8");
console.log(text);Writing a file
writeFile creates or overwrites the file completely.
import { writeFile } from "node:fs/promises";
await writeFile("out.txt", "Hello, file!\n");
console.log("saved");
Output:
saved
Sync vs async
readFileSync blocks the entire event loop until done — fine at startup, risky inside a server handling requests. Prefer the async version there.
Quick check: Why avoid `readFileSync` inside a request handler?
- It throws on missing files
- It blocks the event loop for every other request
- It cannot read text files
Answer
It blocks the event loop for every other request — Sync fs calls freeze Node's single thread — no other request is served until the read finishes.