A Simple HTTP Server

View saved

Listen on a port

Save as server.js and run node server.js.

import http from "http";

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
  res.end("Hello from Node HTTP\n");
});

server.listen(3000, () => {
  console.log("http://localhost:3000");
});

Branch on the path

Read req.url and req.method for basic routing.

if (req.method === "GET" && req.url === "/health") {
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ ok: true }));
  return;
}

Stop the server

Press Ctrl+C in the terminal. For programmatic shutdown, call server.close().

Why frameworks exist

Raw http teaches the basics. Express (next) adds routing, middleware, and helpers you will use in real apps.

Comments

One comment per signed-in account. Comments are saved with this page’s URL.