Creating a Basic HTTP Server in Node.js
A Node.js HTTP server is a listening post that waits for requests on a port and runs your code to reply. It's the foundation for any web service, from simple APIs to full apps. The footgun: forgetting `response.end()` leaves the client hanging indefinitely.
WHY IT EXISTS: The built-in http module allows Node.js to handle web traffic directly, without needing an external web server like Apache or Nginx. Node's event-driven, non-blocking architecture is ideal for building efficient servers that can manage many concurrent connections.
THE MENTAL MODEL: Think of an HTTP server as an object that listens for network connections on a specific port. When a client, like a browser, sends a request to that port, the server emits a 'request' event. You provide a single function, the request listener, that executes every time this event occurs to process the request and generate a response.
HOW IT WORKS: You use the http.createServer() method, passing it a callback function. This function receives two arguments: a request object (IncomingMessage) and a response object (ServerResponse). The request object contains details like the URL, HTTP method, and headers. You use the response object to send data back, setting the status code and headers with response.writeHead() and writing the body with response.write(). Critically, you must call response.end() to signal that the response is complete. Finally, you call server.listen() on the created server object to start listening on a port.
WHEN TO USE IT: Use the raw http module for lightweight, low-level servers where you need minimal overhead and full control. It's excellent for simple microservices, educational purposes, or as the foundation for a custom framework. It gives you direct access to the request and response streams.
WHEN NOT TO USE IT: Avoid the raw http module for complex applications. It lacks essential features like routing, middleware, and advanced error handling. For most production systems, frameworks like Express, Fastify, or Koa are better choices. They use the http module internally but provide a much more productive, higher-level API.
ONE CANONICAL EXAMPLE: First, you require the 'http' module. Then, you call http.createServer(), providing a callback that takes req and res as arguments. Inside this callback, you set the response status code to 200 (res.statusCode = 200), set the content type header (res.setHeader('Content-Type', 'text/plain')), and send the body while closing the connection (res.end('Hello, World!')). Finally, you call server.listen(3000) to start the server on port 3000.
Read the original → nodejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.