Creating a server using NodeJS

NodeJs is one of the most popular server-side frameworks for building web applications. This framework is completely based on the javascript language, which makes it popular among developers. Since developers must learn Javascript while working in frontend development. NodeJs makes the developers happy as they do not have to learn any other language for the server-side and can use Javascript as a server-side language. We have a step-by-step guide on getting started with NodeJs you can refer to it to learn the basics of NodeJS and quickly get started using the framework.

In this tutorial, we will learn how to create a simple HTTP server using NodeJS. To follow this tutorial, you will need to have Node installed in your system. It is also recommended to install an IDE like the cross-platform open-source Visual Studio Code, which is one of the best IDE for writing code, and it will boost the speed of writing code by providing various extensions.

Creating a server using NodeJS

Here, we will create a server to see how the request and response between client and server work in NodeJs. We will use the HTTP module of NodeJs to send requests and receive responses in our server. To create the webserver, we need to create a file with the name index.js and copy the following code in the file.

// importing the http module of Node JS
const http = require('http')
// Creating the Http Server
const server = http.createServer((req, res) => {
    console.log(req.url)
    res.end("Hello World")
})
// Listening the server in the localhost and the port 3000 
server.listen(3000)

Let us see what is going in the above code. The first line of the code is used to import the HTTP module into our code. Next, the require() function in NodeJS is used to grab a package in our code. It is similar to the import or include statement in other programming languages. The require() function accepts a string as the name of the package and returns the package. The http is one of the built-in packages of NodeJs, and it provides functions to create our server. In the next line of the code, we created an http server using the createServer() function of the http module. At the last line of code, we used the listen() method of the server object with the argument 3000, so the server will listen at port 3000.

We can run the app by running the index file using the node command. Then, please run the following command in the terminal to run our server.

node index.js

We can check the server by visiting the URL http://127.0.0.1:3000/. If everything works fine, then we will see something as shown in the below image.

creating our first web server using NodeJs Http module
creating our first web server using NodeJs HTTP module

In the above Image, we have seen the Hello World response as we write the code res.end(“Hello World”) while creating the server. You can change this text with any other content and re-run the code to see how it works.

The Server we made works fine, but it has only one route, i.e., http://127.0.0.1:3000/, so if we go to other routes such as http://127.0.0.1:3000/about, we will get the same content as present in the http://127.0.0.1:3000/ page. But while building a website, we need to use different routes for pages like the about page, contact page, etc. So now, let us see how we can provide different routes to our server.

Building Routes

To build routes for our server, we need to use the if statement of javascript to compare the route req.url with the string of the required route. The following code shows how to create specific routes and send different responses for different routes using NodeJS.

// importing the http module of Node JS
const http = require('http')

// Creating the Http Server
const server = http.createServer((req, res) => {
    console.log(req.url)
    // Building the Routes for the server
    if (req.url === '/') {
        res.end("Welcome To Home Page")
    }
    else if (req.url === '/about') {
        res.end("Welcome to the About Page")
    }
    else if (req.url === '/contact') {
        res.end("Welcome to the Contact Page")
    }
    else if (req.url === '/blog') {
        res.end("Welcome to the Blog Page")
    }
    else {
        // If the rout will not match then it will show the following error
        res.writeHead(404)
        res.end('page not found')
    }
})
// Listening the server in the localhost and the port 3000 
server.listen(3000)

In the above code, we have created three extra routes, namely, /about, /contact, /blog for the about, contact, and the blog page. You can check the routes by running the above code and visiting different routes such as http://127.0.0.1:3000/about, http://127.0.0.1:3000/contact, and http://127.0.0.1:3000/blog. If you visit a route that we have not created, it will show the message as shown in the below image.

building custom routes in our web server using Node JS
building custom routes in our web server using Node JS

Till now, we have built a server that only returns text as a response. But while building a website, we need to send our response in HTML or JSON text. So let us now see how to serve custom HTML pages with the help of NodeJs.

Serving HTML files

In the current folder, create some HTML files with the name index.html, about.html, and contact.html. Then add some HTML content in each of these files, such as in the index.html file, add the following HTML content.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HomePage</title>
</head>
<body>
    <h1>HomePage</h1>
    <p>Welcome to the Home page</p>
</body>
</html>

In the about.html, write the following Html content.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AboutPage</title>
</head>
<body>
    <h1>AboutPage</h1>
    <p>Welcome to the About page</p>
</body>
</html>

Next, in the contact.html file, add the following HTML content.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ContactPage</title>
</head>
<body>
    <h1>ContactPage</h1>
    <p>Welcome to the Contact page</p>
</body>
</html>

After creating the three HTML files, we need to use them in the index.js file to serve them on our server. We were going to use the fs module of NodeJS. The fs module of NodeJs is used to work with files in our server. The complete code for serving the Html files is shown below.

// importing the http module of Node JS
const http = require('http')
// importing the fs module of Node JS
const fs = require('fs')
// reading the content of the HTML files
const indexPage = fs.readFileSync('index.html')
const aboutPage = fs.readFileSync('about.html')
const contactPage = fs.readFileSync('contact.html')
// Creating the Http Server
const server = http.createServer((req, res) => {
    console.log(req.url)
    // Building the Routes for the server
    if (req.url === '/') {
        // serving the index.html page
        res.end(indexPage)
    }
    else if (req.url === '/about') {
        // serving the about.html page
        res.end(aboutPage)
    }
    else if (req.url === '/contact') {
        // serving the contact.html page
        res.end(contactPage)
    }
    else {
        // If the rout will not match then it will show the following error
        res.writeHead(404)
        res.end('page not found')
    }
})
// Listening the server in the localhost and the port 3000 
server.listen(3000)

In the above code, we first import the fs module required to read server-side files in NodeJs. The fs module contains a function readFileSync that can be used to read a file and returns the file’s content. Next, we store the content of the files in some variables and serve the content using the res.end() function. Finally, we can run the server by executing the command node index.js. After running the server, if we go to page URL http://127.0.0.1:3000/, we will see the index page served as the web page. The below image shows how the home page looks like.

Serving an Html file using fs and http modules of NodeJs
Serving an Html file using fs and HTTP modules of NodeJs

You can also look at the other pages like the contact page and about page by visiting the URLs http://127.0.0.1:3000/about and http://127.0.0.1:3000/contact, respectively.

Conclusion

In this tutorial, we learn how to create a server using NodeJs. We start by building a simple server that sends the same response to all URLs. After that, we improve the server by providing different routes to the server. At last, we learn how to serve HTML pages with the help of the server. You may also like to see a step-by-step guide on creating a web app in Python using Flask.

Similar Posts

One Comment

Leave a Reply

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