Course outline · 0% complete

0/29 lessons0%

Course overview →

http.createServer, Line by Line

lesson 3-1 · ~10 min · 8/29

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).
  • req describes the request: req.method, req.url, req.headers.
  • res is how you answer: res.writeHead(status, headers) then res.end(body).
  • listen(3000) claims port 3000, the routing number from lesson 1-2: from this moment the operating system delivers every connection addressed to localhost:3000 to this process. If another program already holds the port, listen fails with the famous EADDRINUSE error.

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.

requestGET /healthcreateServercallbackroute()your pure logicres.endreply
Keep the decision logic in a plain function. The http wiring stays thin, and the interesting part stays testable.

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.