How to Create an HTTP Server in Node.js?

1. Definition

In Node.js, an HTTP server is created using the built-in http module. It allows you to handle client requests and send responses over the web.

2. Steps to Create Server

  • Import http module
  • Create server using createServer()
  • Handle request and response
  • Start server using listen()

3. Example

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello World");
});

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

4. How it Works

  • Client sends request to server
  • Server processes request
  • Server sends response back

5. Output

Open browser → http://localhost:3000

Output:
Hello World

6. Advantages

  • Simple and lightweight
  • No external libraries needed
  • Good for learning backend basics
  • Highly scalable