Node.js: Code Outside the Browser / HTTP Module-Creating a Web Server (No Express)

http module and creating a basic server

πŸ“¦ The http Module

http is a built-in Node.js module for building a web server β€” no extra install, no framework like Express required.

Think of it like a restaurant waiter: customers (browsers) place orders (requests), and the waiter (your server) brings back the right dish (a response). The http module is what lets Node.js play that role β€” receiving requests and sending something back.

With it, you can:

  • πŸ‘‚ Listen for incoming HTTP requests

  • πŸ“€ Respond with text, HTML, JSON, or files

  • 🧭 Handle different routes, like /home or /about

import { createServer } from 'node:http';

πŸš€ Creating a Basic Server

A minimal server that replies "Hello, World!" to every visitor.

// index.js
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  res.write('Hello, World!');
  res.end();
});

server.listen(3000, () => {
  console.log('Server is running at <http://localhost:3000>');
});
  • createServer(callback) sets up the server. The callback runs once per incoming request, and receives two objects:

    • req β€” the incoming request (URL, method, headers, etc.)

    • res β€” the response you build and send back

  • res.write(text) adds content to the response body. You can call it more than once to send content in pieces.

  • res.end() finishes the response and sends it to the browser. Without this, the browser keeps waiting and the page never finishes loading.

  • server.listen(3000, callback) starts the server on port 3000 β€” the callback runs once, right after the server is ready.


▢️ How to Run It

  • Open a terminal in your project folder

  • Run:

    node index.js
  • Visit http://localhost:3000 in your browser

  • βœ… You'll see: Hello, World!

Terminal output:

Server is running at <http://localhost:3000>

Browser output:

Hello, World!