An HTTP server in JavaScript
createServer, a request handler, and JSON out.
import { createServer } from "node:http";
const routes = {
"/healthz": () => ({ status: "ok" }),
"/tours": () => ({ tours: ["basics", "async", "node"] }),
};
const server = createServer((request, response) => {
const handler = routes[new URL(request.url, "http://localhost").pathname];
if (!handler) {
response.writeHead(404, { "Content-Type": "application/json" });
response.end(JSON.stringify({ error: "not found" }));
return;
}
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(handler()));
});
server.listen(0, () => {
console.log("listening on", server.address().port > 0);
server.close();
});
How it works
- The handler gets the request and the response.
- Write the status and headers before the body.
server.closestops accepting, then finishes in flight.
Keywords and builtins used here
JSONconstfromifimportreturn
The run, in numbers
- Lines
- 22
- Characters to type
- 644
- Tokens
- 179
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 98 seconds.
Step 1 of 3 in Network, step 12 of 18 in Node.js.