components/walkthrough/

plays once in view

server.ts
import { createServer } from "node:http"import { readFile } from "node:fs/promises"import { join } from "node:path"const PORT = Number(process.env.PORT ?? 3000)const ROOT = join(import.meta.dirname, "public")type Handler = (url: URL) => Promise<Response>const TYPES: Record<string, string> = {  html: "text/html",  css: "text/css",  js: "text/javascript",  svg: "image/svg+xml",}function typeOf(path: string): string {  const ext = path.split(".").at(-1) ?? ""  return TYPES[ext] ?? "application/octet-stream"}const routes: Record<string, Handler> = {  "/health": async () => new Response("ok"),  "/time": async () => Response.json({ now: Date.now() }),}async function files(url: URL): Promise<Response> {  const path = join(ROOT, url.pathname)  if (!path.startsWith(ROOT)) return new Response("no", { status: 403 })  const body = await readFile(path)  return new Response(body, {    headers: { "content-type": typeOf(path) },  })}async function handle(url: URL): Promise<Response> {  const route = routes[url.pathname]  if (route) return route(url)  return files(url)}const server = createServer(async (req, res) => {  const url = new URL(req.url ?? "/", `http://${req.headers.host}`)  const answer = await handle(url)  res.writeHead(answer.status, Object.fromEntries(answer.headers))  res.end(Buffer.from(await answer.arrayBuffer()))})server.listen(PORT, () => {  console.log(`listening on ${PORT}`)})

a small server

Fifty lines of Node: no framework, the standard library and nothing else.

routes are data

A route is a path and a function that answers it. Adding one is adding a line.

everything else is a file

What no route answers is read from disk, and a path that climbs out of the folder is refused.

answered on the way out

Each request becomes a URL, the answer a standard Response, written back to Node's socket.

a missing file

A file that is not there would throw. Now it answers 404, two lines in place of one.

and its test

The change, asked for from outside.