Node.js Web Server

Node.js is a powerful JavaScript runtime that enables developers to build scalable and efficient web servers. In this article, we’ll walk through the steps to create a simple web server using Node.js, covering the basics and providing a foundation for more advanced applications.

Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hypertext Transfer Protocol (HTTP). The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.

Setting Up Your Project

Step 1: Create a Project Directory

Start by creating a new directory for your project and navigate into it:

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

Step 2: Initialize a Node.js Project

Initialize a new Node.js project using npm

npm init -y

This command creates a package.json file with default settings.

Building the Web Server

Step 1: Create the Server File

Create a file named server.js in your project directory. This file will contain the code for your web server.

Step 2: Import Required Modules

At the top of server.js, import the http module, which is built into Node.js.

const http = require('http');

Step 3: Create the Server

Use the http module to create a server. The createServer method takes a callback function that is executed whenever a request is received

const server = http.createServer((req, res) => {
res.statusCode = 200; // Set the status code to 200 (OK)
res.setHeader('Content-Type', 'text/plain'); // Set the content type to plain text
res.end('Hello, World!\n'); // Send a response
});

Stpe 4: Specify the Port and Start the Server

Define the port the server will listen on and start the server

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

Step 5: Complete server.js

Your server.js file should now look like this

const http = require('http');

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});

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

Run the Server

In your terminal, run the server using Node.js

node server.js

Example 1: Implementation to show the web server creation in Node.js. 

Node
// Import the Node.js http module
const http = require('http');

// req is the request object which is
// coming from the client side
// res is the response object which is going
// to client as response from the server

// Create a server object
http.createServer(function (req, res) {

    // 200 is the status code which means
    // All OK and the second argument is
    // the object of response header.
    res.writeHead(200, { 'Content-Type': 'text/html' });

    // Write a response to the client
    res.write('Congrats you have a created a web server');

    // End the response
    res.end();

}).listen(8081); // Server object listens on port 8081

console.log('Node.js web server at port 8081 is running..')

Run the Server

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

node server.js

 

The http.createServer() method includes a request object that can be used to get information about the current HTTP request e.g. url, request header, and data. 

Example: The following example demonstrates handling HTTP requests and responses in Node.js. 

Node
// Import Node.js core module i.e http
const http = require('http');

// Create web server
const server = http.createServer(function (req, res) {

    // Check the URL of the current request
    if (req.url == '/') {

        // Set response header
        res.writeHead(200, { 'Content-Type': 'text/html' });

        // Set response content    
        res.write(
            `<html><body style="text-align:center;">
            <h1 style="color:green;">w3wiki Home Page</h1>
            <p>A computer science portal</p>
            </body></html>`);
        res.end();//end the response

    }
    else if (req.url == "/webtech") {

        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(`
        <html><body style="text-align:center;">
            <h1 style="color:green;">Welcome to w3wiki</h1>
            <a href="https://www.w3wiki.net/web-technology/">
            Read Web Technology content
            </a>
        </body></html>`);
        res.end();//end the response

    }
    else if (req.url == "/DS") {

        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(`<html><body style="text-align:center;">
        <h1 style="color:green;">w3wiki</h1>
        <a href="https://www.w3wiki.net/data-structures/">
            Read Data Structures Content
        </a>
        </body></html>`);
        res.end(); //end the response

    }
    else if (req.url == "/algo") {

        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(`<html><body style="text-align:center;">
        <h1 style="color:green;">w3wiki</h1>
        <a href="https://www.w3wiki.net/fundamentals-of-algorithms/">
        Read Algorithm analysis and Design Content
        </a>
    </body></html>`);
        res.end(); //end the response

    }
    else
        res.end('Invalid Request!'); //end the response

    // Server object listens on port 8081
}).listen(3000, () => console.log('Server running on port 3000'));

In the above example, req.url is used to check the url of the current request, and based on that it sends the response. 

Command to Run code:

node index.js

URL: localhost:3000/webtech

URL: localhost:3000/DS

URL: localhost:3000/algo