Simple http web server with Node.js

This page explains how to create a very simple web server with Node.js. How to create a fresh Node.js project and start a simple http server. The source code is detailed and explained.

The following has been tested with Node.js v18.13.0 on Ubuntu 22.04.

Workspace

Let's start by creating a folder server for our project:

mkdir server

Go in the project folder

cd server

Create and edit new file named server.js

touch server.js

Source code

Here is the source code for the server, copy and past the code in the file server.js

// Import http module
var http = require('http'); 

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

    // Home page
    if (req.url == '/') {         
        // Set response for home page
        res.writeHead(200, { 'Content-Type': 'text/html' });         
        res.write('<html><body><h1>Home Page</h1></body></html>');
        res.end();

    }    
    else if (req.url == "/contact") {        
        // Set response for contact page
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('<html><body><h1>Contact page</h1></body></html>');
        res.end();

    }
    else if (req.url == "/json") {        
        // Set JSON content
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.write('{"name":"John","age":30,"cars":["Ford", "BMW", "Fiat"]}');
        res.end();       
    }
    else {
        res.writeHead(404); 
        res.end('Page not found!');
    }

});

// Listen for incoming requests on port 3000
server.listen(3000); 
console.log('Node.js web server listening on port 3000.')

Explanation

First, let's import the http module used for created an http server:

var http = require('http'); 

With the http module, create a new server with createServer():

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

The parameter of the function is another function. This callback function is exectuted every time the server received an http request. The two parameters of the functions are:

In the callback function, let's check if the client requested the home page. If the url requested (req.url) is /, the server send back the home page:

// Home page
if (req.url == '/') {         
    // Set response for home page
    res.writeHead(200, { 'Content-Type': 'text/html' });         
    res.write('<html><body><h1>Home Page</h1></body></html>');
    res.end();

}    

The HTTP 200 OK success status response code indicates that the request has succeeded. 'Content-Type': 'text/html' specify we serve an HTML page. res.write() is write the page content in the response (here the HTML home page). Finally res.end() ends the response process.

If the home page is not request, we check for another path, for example /contact/

else if (req.url == "/contact") {        
    // Set response for contact page
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write('<html><body><h1>Contact page</h1></body></html>');
    res.end();

}

In the same way, we can server JSON by modifying the page content:

else if (req.url == "/json") {        
    // Set JSON content
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write('{"name":"John","age":30,"cars":["Ford", "BMW", "Fiat"]}');
    res.end();       
}

If none of the previous pages was requested, we serve the 404 error page:

else {
    res.writeHead(404); 
    res.end('Page not found!');
}

After creating the http server, we have to specify the port. Usualy, the http port 80, but this port is already used by Internet, so we choose 3000:

server.listen(3000); 

This last line start listening for http request. Every time a request is received, the callback function is executed.

Start the server

To start the server, simply run the following command:

node server.js

Go to your browser and check the URL http://localhost:3000:

Home page the http web server created with Node.js

http://localhost:3000/contact:

Contact page the http web server created with Node.js

http://localhost:3000/json:

JSON content served by the http web server created with Node.js

Download

You can download the Node.js Web server source code:

server.js

See also


Last update : 01/11/2023