Lesson 10 / 30

The fs Module

Read and write files with the fs/promises API, and avoid blocking the event loop with synchronous calls.

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 cannot read text files
  • It blocks the event loop for every other request
  • It only works on Windows
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.