Node.js

Lesson 02

Async filesystem without blocking

Use async filesystem APIs in request paths so one slow disk read does not block the event loop.

Good Code

src/routes/config.ts
import { readFile } from "node:fs/promises";
import type { ServerResponse } from "node:http";

export async function sendPublicConfig(response: ServerResponse) {
  const file = await readFile("public-config.json", "utf8");

  response.setHeader("content-type", "application/json");
  response.end(file);
}

Bad Code

src/routes/config.ts
import { readFileSync } from "node:fs";
import type { ServerResponse } from "node:http";

export function sendPublicConfig(response: ServerResponse) {
  const file = readFileSync("public-config.json", "utf8");

  response.setHeader("content-type", "application/json");
  response.end(file);
}

Review Notes

What to review

Good Code

The good version awaits an async file read and lets the event loop continue handling other work while the disk is busy.

Bad Code

The bad version uses readFileSync in a request path, blocking every other request in the process until the read finishes.

Takeaways

  • Avoid synchronous filesystem calls inside HTTP handlers and other hot paths.