Quiz
Warm-up from lesson 2-3. You wrote process.stdin.on("data", callback). What does .on generally mean in Node?
A real server in nine lines
Node's built-in http module turns your request-to-response function into an actual network server:
const http = require("node:http"); const server = http.createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("Hello from Node!"); }); server.listen(3000, () => { console.log("listening on http://localhost:3000"); });
createServer(callback)builds a server. The callback runs once per incoming request (there is the event loop again).reqdescribes the request:req.method,req.url,req.headers.resis how you answer:res.writeHead(status, headers)thenres.end(body).listen(3000)claims port 3000, the routing number from lesson 1-2: from this moment the operating system delivers every connection addressed tolocalhost:3000to this process. If another program already holds the port,listenfails with the famousEADDRINUSEerror.
Save it as server.js, run node server.js on your own machine, and open http://localhost:3000 in a browser. This sandbox cannot open network ports, so server wiring is shown as reading code, while everything the server does stays runnable.
Separate the wiring from the logic
Professional Node code keeps the http wiring thin and pushes decisions into plain functions:
const server = http.createServer((req, res) => { const [status, body] = route(req.method, req.url); res.writeHead(status, { "Content-Type": "text/plain" }); res.end(body); });
Now route is just JavaScript. You can run it, test it, and reason about it with no server at all, which is exactly what you did in lesson 1-1 with handle. Build it below.
Code exercise · javascript
Your turn. Complete route so that GET /health returns [200, "ok"] and POST /users returns [201, "user created"]. Anything else stays 404. The loop at the bottom exercises all three cases.