Building a Simple Web Server with Node.js and HTTP Module

Node.js provides a built-in HTTP module that allows developers to create web servers without needing external libraries. This makes it easy to build lightweight and scalable applications. In this guide, we’ll walk through creating a basic web server using Node.js and the HTTP module.


1. Setting Up Node.js

Before starting, ensure that Node.js is installed on your system.

1.1 Install Node.js

Download and install Node.js from the official website:
https://nodejs.org/

1.2 Verify Installation

After installation, check if Node.js and npm are installed by running:

node -v  # Check Node.js version
npm -v   # Check npm version

2. Creating a Basic Web Server

2.1 Create a New Project Directory

Navigate to your preferred folder and create a new directory:

mkdir node-web-server
cd node-web-server

2.2 Create a JavaScript File

Inside the project directory, create a new file named server.js:

touch server.js

2.3 Writing the Web Server Code

Open server.js in a code editor and add the following code:

const http = require('http'); // Import the HTTP module

// Define the server port
const PORT = 3000;

// Create a server
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' }); // Set response header
    res.end('Hello, World! This is my first Node.js server.\n'); // Send response
});

// Start the server
server.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

2.4 Running the Server

To start the server, open a terminal and run:

node server.js

You should see output like:

Server is running on http://localhost:3000

3. Handling Different Routes

Modify the server.js file to handle different routes based on the request URL.

const http = require('http');

const PORT = 3000;

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

    if (req.url === '/') {
        res.end('Welcome to the Home Page!');
    } else if (req.url === '/about') {
        res.end('This is the About Page.');
    } else if (req.url === '/contact') {
        res.end('Contact us at contact@example.com.');
    } else {
        res.writeHead(404);
        res.end('404 Not Found');
    }
});

server.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Testing the Routes

  • Open a browser and go to http://localhost:3000/ → Displays Welcome to the Home Page!

  • Visit http://localhost:3000/about → Displays This is the About Page.

  • Visit http://localhost:3000/contact → Displays Contact us at contact@example.com.

  • Visit http://localhost:3000/unknown → Displays 404 Not Found.


4. Serving HTML Files Instead of Plain Text

To serve HTML files, update server.js to use the fs (File System) module.

4.1 Create HTML Files

Inside the project directory, create a new folder views and add the following files:

views/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
</head>
<body>
    <h1>Welcome to My Node.js Web Server</h1>
</body>
</html>

views/about.html

<!DOCTYPE html>
<html>
<head>
    <title>About Page</title>
</head>
<body>
    <h1>About Us</h1>
    <p>This is a simple web server built with Node.js.</p>
</body>
</html>

4.2 Update server.js to Serve HTML Files

Modify server.js to serve the HTML files:

const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = 3000;

const server = http.createServer((req, res) => {
    let filePath = '';

    if (req.url === '/') {
        filePath = path.join(__dirname, 'views', 'index.html');
    } else if (req.url === '/about') {
        filePath = path.join(__dirname, 'views', 'about.html');
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        return res.end('404 Not Found');
    }

    fs.readFile(filePath, (err, content) => {
        if (err) {
            res.writeHead(500, { 'Content-Type': 'text/plain' });
            res.end('Server Error');
        } else {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(content);
        }
    });
});

server.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Testing the Updated Server

  • Visit http://localhost:3000/ → Displays the Home Page HTML.

  • Visit http://localhost:3000/about → Displays the About Page HTML.

  • Visit http://localhost:3000/unknown → Displays 404 Not Found.


5. Best Practices for Node.js Web Servers

  1. Use Environment Variables: Store configuration settings (e.g., port numbers) in .env files.

  2. Handle Errors Properly: Always check for errors when using fs.readFile() or other asynchronous functions.

  3. Use a Framework for Large Applications: Express.js simplifies routing and middleware handling.

  4. Enable Logging: Use console.log() or logging libraries like Winston for debugging.

  5. Optimize Performance: Use caching mechanisms and avoid blocking the event loop.


6. Conclusion

You have successfully built a simple web server using Node.js and the HTTP module. You also learned how to handle routes, serve HTML files, and apply best practices.

Related post

Leave a Reply

Your email address will not be published. Required fields are marked *