Building a Simple HTTP Server in Node.js: A Step-by-Step Guide

67 views

Sure! Building a simple HTTP server in Node.js without using any libraries like Express.js is straightforward because Node.js has a built-in http module. Here’s a step-by-step guide:

Step 1: Setting Up Your Environment

  1. Make sure you have Node.js installed. You can download it from nodejs.org.

Step 2: Create a New Project

  1. Create a new directory for your project:

    mkdir simple-node-server
    cd simple-node-server
    
  2. Initialize a new Node.js project:

    npm init -y
    

Step 3: Building the HTTP Server

  1. Create a new file named server.js:

    touch server.js
    
  2. Open server.js in your preferred text editor and add the following code:

const http = require('http');

// Define the hostname and port the server will listen on
const hostname = '127.0.0.1';
const port = 3000;

// Create the server
const server = http.createServer((req, res) => {
  // Set the response header with HTTP status and Content-Type
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');

  // Basic routing
  if (req.method === 'GET' && req.url === '/') {
    res.end('Hello, World!\n');
  } else if (req.method === 'GET' && req.url === '/about') {
    res.end('About Page\n');
  } else {
    // Default case for unhandled routes
    res.statusCode = 404;
    res.end('Not Found\n');
  }
});

// Start the server and listen on the defined hostname and port
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Step 4: Running the Server

  1. In your terminal, run the server using Node.js:

    node server.js
    
  2. You should see the following output in your terminal:

    Server running at http://127.0.0.1:3000/
    

Step 5: Testing the Server

  1. Open your web browser or use a tool like curl to test the server:
    • Visit http://127.0.0.1:3000/ to see the "Hello, World!" message.
    • Visit http://127.0.0.1:3000/about to see the "About Page" message.
    • Visit any other URL to see the "Not Found" message.

Explanation of the Code

  1. Require http Module:

    const http = require('http');
    
    • This line imports the built-in http module which contains the necessary functions to create an HTTP server.
  2. Define Hostname and Port:

    const hostname = '127.0.0.1';
    const port = 3000;
    
    • These lines define the hostname and port number where the server will be accessible.
  3. Create the Server:

    const server = http.createServer((req, res) => {
    
    • This line creates the server and specifies a request handler function that will be called whenever a request is received.
  4. Set Response Header and Status Code:

    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    
    • These lines set the HTTP status code to 200 OK and set the Content-Type header to text/plain.
  5. Basic Routing:

    if (req.method === 'GET' && req.url === '/') { ... }
    
    • This block checks the request method and URL and responds accordingly.
  6. Start the Server:

    server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}/`);
    });
    
    • This line starts the server and logs a message once it is running.

By following these steps, you’ve created a simple HTTP server using Node.js's built-in http module without any external libraries like Express.js. You can further extend this basic server to handle more complex routes and functionality as needed.