Lesson 15 / 28
The http Module
Create a server and route requests without any framework.
A minimal server
http.createServer takes a callback that runs for every incoming request.
import http from "node:http";
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, Node server!");
});
server.listen(3000, () => {
console.log("Listening on http://localhost:3000");
});
Output:
Listening on http://localhost:3000
Routing manually
Without a framework, you branch on req.method and req.url yourself.
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
res.end("Home page");
} else if (req.method === "GET" && req.url === "/about") {
res.end("About page");
} else {
res.writeHead(404);
res.end("Not found");
}
});Frameworks exist for a reason
Manual routing gets messy fast — frameworks like Express layer clean routing, middleware, and parsing on top of this same http module.
Quick check: What does res.end() do?
- Starts the server
- Sends the response and closes it
- Deletes the request
Answer
Sends the response and closes it — `res.end()` finishes sending the response body; no more data can be written to it afterward.