Create a simple NODE JS web server

In this article, we will learn how to create a web server in Node.js

Introduction

Before starting with the creation of node.js web server, let us go through few important details like installation and other details.

Node Installation

Before starting, make sure to install Node.js in the system. We can download the latest version from https://nodejs.org.

Once downloaded, install the node.js to your system.

To check the installed node version we can use the command “node -v” in the terminal. The output of the command displays the installed node.js version.

node version installed

Installation of node.js also installs a package manager called npm. This package manager manages the node modules.

Node Modules

A javascript file or a bundle of javascript files forms a node module. Other javascript files import the node modules before using them.

Exporting the module with the help of the export keyword makes the module functions and properties available for import on other javascript files.

We can use the require() function to import a node module inside a javascript file.

We will use the HTTP module of node.js to create the webserver and handle the incoming requests.

NPM commands

The npm commands can be used to add, update or remove a node package while creating the node applications.

Few of the important npm commands are

  • npm init: Initialize a node.js application and creates a package.json file.
  • npm install <package>: Installs a node.js package.
  • npm start: Starts the node application(provided required package.json setup is available)

Build a web server with node js

As we have learned the basics of node and npm, let us create a simple web server now.

Initialization of the node application

To get started, create a directory with the name my_node_server and navigate inside the directory.

Run the npm command “npm init” to initialize the node application.

This will prompt for few details about the application. Fill in the details and a package.json file is created under the application’s directory.

node-web-server-example

Creating the node web server

The node.js code library contains the http node module. We will use the http node module to create the webserver.

We will use the http-status-codes package to get the constant HTTP response codes.

Run the npm command “npm install http-status-codes -save” to install the module.

We can also use the shorthand version of the command “npm i http-status-codes -s” instead.

The -save command adds the package as an application dependency.

install http status codes package.

Create a new javascript file with the name main.js and add below given content.

const port = 3000,
http = require("http"),
httpStatus = require("http-status-codes"),
app = http.createServer((request, response) => {
    console.log("Recieving an incoming request!");
    response.writeHead(httpStatus.StatusCodes.OK, {
        "Content-Type": "text/html"
    });

    let responseMessage = "<h1>Hello Universe!</h1>";
    response.write(responseMessage);
    response.end();
    console.log(`Response is sent:${responseMessage}`);
})

app.listen(port);
console.log(`The server has started and is listening on port number:${port}`);
  • We are assigning port number 3000 to the node web server on line number one.
  • We imported the http and http-status-codes node modules.
  • The createServer() function of the http module helps us create the webserver instance.
  • In case of any event occurs that triggers the execution of the createServer callback function. The event can be invoking the sever running at port 3000 on a browser(HTTP GET request event).
  • We are setting the response content type value to “text/html”.
  • The message to the response body can be written with the help of the response.write() function.
  • Finally, we are calling the end() function on response to complete the response.

Run the application by executing the command “node .\main.js“.

execute run node web server

We can access the web server at localhost:3000

node js web server example

Retrieving the request details

We can retrieve the request details such as request URL, headers, etc from the request instance as shown below.

console.log(request.method);        
console.log(request.url);           
console.log(request.headers);

Serving the static files

We can serve the static files like HTML, CSS, etc with the help of node’s fs module.

Create a folder called static_files on project directory and add a HTML file as shown below.

<!DOCTYPE html>
<html>                       
  <head>
    <meta charset="utf-8">
    <title>Content page</title>
  </head>
  <body>
    <h1>Hello Universe!</h1>
  </body>
</html>

Now modify the main.js file with below content.

const port = 3000,
    http = require("http"),
    fs = require("fs"),
    httpStatus = require("http-status-codes"),
    routes = {
        "/": "satic_files/content.html"
    },
    app = http.createServer((request, response) => {
    console.log("Recieving an incoming request!");

    console.log(request.method);
    console.log(request.url);
    console.log(request.headers);

    response.writeHead(httpStatus.StatusCodes.OK, {
        "Content-Type": "text/html"
    });
    if (routes[request.url]) {
        fs.readFile(routes[request.url], (error, data) => {
            response.write(data);
            response.end();
        });
    } else {
        response.end("<h1>Sorry, page not found.</h1>");
    }
});

app.listen(port);
console.log(`The server has started and is listening on port number:${port}`);
  • Node.js provides the fs code module to access the files. We imported the fs module to serve the static file content.html in our example.
  • The routes key/value pair is used to determine the static file to be returned based on the request on the URL path.
  • As we are invoking only a static HTML page, the contentType header response is set with the value “text/html”.
  • We can access the static file using the readFile() function of the fs node module. The function takes a file path as input and provides a callback function that contains the error or file data.
  • Whenever an URL is invoked, if the URL path is / static HTML file content is returned in the response.
  • Whenever URL paths other than / are invoked, an error message is returned in the response.

Below image shows the output of the node web server.

node js web server example

Invoking the URLs other than / results n error message as shown.

node js web server example

This example shows only how to return static HTML content. To support other file types such as image/CSS, etc, we need to set the suitable HTTP response header.

Conclusion

In this article, we learned how to create a node.js web server.

We also learned basic details about npm commands and node modules and how to import them to use them in our node application.

We also learned how to use the http node module to handle the HTTP requests and how to serve the static files with the help of the fs node module.

The code is available on the Github.

You may also interested in

Leave a Reply