How to Create a Web Server in Nodejs?

Konfinity
March 3,2021 - 9 min read
How to Create a Web Server in Nodejs?

While surfing the internet, one common action by users is to either view a webpage on the browser or make a request to another computer on the internet and the response to this request is the particular webpage. The computer, here is the medium by which the customer talks to the internet.

In this entire concept of web server, HTTP request and response is important. HTTP requests are received by the server and sent by a client. Often, HTTP request is sent by the browser and the HTTP response can be an HTML page or JSON from an API.

While making a web server, the frontend and backend code is involved. The front-end code looks after the presentation of the content and the back-end code is responsible for the exchanging, processing and storing of data. The back-end also handles the network requests from the browser as well as the communication with the database. In today’s blog, we are going to briefly look at the entire process of making a web server in Nodejs with the help of the HTTP module. Let’s get started!

Creating a Web Server

Now that we know that front-end and back-end is both involved in the creation of a web server and hence it is easy for developers to write a code for a web server in Nodejs as it provides both the frontend and backend together. Hence, Nodejs is a popular choice to make a web server. In this blog, we will learn how to build web servers in Nodejs with the help of the http module. As a part of this blog, we will build web servers returning simple text. However, you can create web servers that return JSON data, CSV files, and HTML web pages also.

Before starting, make sure that you have Node.js installed. Along with the installation of the latest version, developers should also know the basics of Node.js. Some important concepts to learn is asynchronous programming and the file system module for interacting with files in Nodejs. Once, you are done with all the basics, you are good to go, so let’s get started!

The first step is to create a HTTP Server, to begin with, you can create a simple one that returns a plain text. This basic step will help you understand the key concepts necessary for setting up a server.

In Nodejs, it is important to create a coding environment. Let’s begin by creating a folder, we’ll name our folder, ‘konfinity-server’. The syntax for the same will look like - mkdir konfinity-servers. After we have made the directory, we change our directory with the code cd konfinity-servers. The next step is to create a file for the code and the syntax for the same will be ‘touch webdev.js’

Now, the next step is to open the file in any text editor that is available on the terminal. The syntax is simple, you have to write the name of the text editor followed by the file name.

The first step in the text editor is to load the http module that is compliant with all Node.js installations. The syntax for including the module is konfinity-servers/webdev.js const http = require("http");

The HTTP or the Hyper Text Transfer Protocol Module in Nodejs allows the transfer of data over HTTP in any Nodejs application. It has the function to create the server. As a part of a next few steps, two constants will be defined. These are the host and port and our server will be bound to these constants. The syntax is very simple, it is – ‘const host = localhost' for the host and ‘const port = 8080’ for the port.

Localhost is a special private address. It is used by computers to refer to themselves and is generally equivalent of the internal IP address. It is available to the local computer only and not to any other local network over the internet.

On the other hand, port number is used by the servers as an endpoint or “door” to our IP address. For the example of this blog, we use port 8080 for our web server which is typically used for development. Now, the host and the port are bind to the server, the server can be reached by accessing http://localhost:8080 in a local browser.

The main reason behind the presence of web servers is to accept requests from browsers and other clients as well. The interaction with the web server is by entering a domain name. The DNS server translates the domain to an IP address which is a unique sequence that identifies a computing resource on a network, for example, internet.

The next step will be to add a function, request listener. This function handles incoming HTTP requests and returns HTTP responses. A request listener has two arguments. It contains a request object that captures data coming in from the HTTP request and a response object that returns HTTP responses for the web server.

Let’s write the code for displaying the message “Web Development at Konfinity” whenever someone accesses the web server.

  • Konfinity-server/webdev.js
  • const requestListener1 = function (req1, res1) { res.writeHead(200);
  • res.end("Web Development at Konfinity");
  • };

The response and request are the two arguments that request listener accepts. In the code above, the request object captures the HTTP request that the user sends is captured in a Request object, whereas the response object interacts with the user and returns the HTTP response.

The HTTP status code is set up by the code -res.writeHead(200). It indicates the status of the HTTP request and its handling by the server. In our example, code 200 means "OK".

The next line, res.end("Web Development at Konfinity"); is used for returning the HTTP response to the client who requested it. This function is capable of returning any type of data the server has to return. In our example, it’s returning a text data.

As a next step, we have to make use of the request listener and create a server of your own. The code below explains the creation of server.

  • first-servers/hello.js
  • const server = http.createServer(requestListener1);
  • server.listen(port, host, () => { console.log(`The server you created is running on http://${host}:${port}`);
  • };

In the code above, the first line is used to create a new server object with the use of createServer () function of the http module. The HTTP request is accepted by the server and it is passed on to the requestListener1 () function created earlier.

Now, after the server is created, it has to be bind to a network address with the help of the server.listen() method which accepts three arguments - port, host, and a callback function. The callback function, or the third argument, displays a message to the console. This is required to know when the server has begun listening to the connections.

However, in the server.listen () method, these arguments are optional. It is a good practice to explicitly state the type of port and host a web server should use. The port and host are required to set up load balancing when deploying web servers to different environments.

One important thing to note is that the requestListener1() might not use the req1 object, it will still be the first argument of the requestListener1() function.

Now, we have created our very own web server with minimum number of lines possible, it’s time to see and test our code in action by running the program. When we would write node webdev.js, the output on the console would be – ‘The server you created is running on http://localhost:8000’

You would observe that the prompt will disappear, the reason is that Node.js server is a long running process and only exits if it encounters an error because of which it will crash and quit or it stops if we explicitly stop the Node.js process from running the web server.

cURL is a command line interface tool used to communicate with the server in a separate terminal window. This tool is used to transfer data to and from a particular network. The command used to make an HTTP GET request to the running web server is - curl http://localhost:8000. The output on the terminal of the following command would be - Web Development at Konfinity.

Congratulations! We have just made our very own server and got the first server response. It is now time to understand the behind the scenes of testing the server.

First of all, the Curl tool was used to send a GET request to the server at http://localhost:8000. The server listened to the connections from that address and passed the request to the requestListener() function which in turn returned text data with the particular status code ‘200’. As a last step, the server sent the response back to cURL. It displayed our particular message on the terminal.

As the terminal step, we have to exit the running server by simply pressing two keyboard keys simultaneously CTRL+C which will interrupt the server’s execution and bring us back to the command line prompt.

With this we come to an end of the server we created ourselves. However, when we visit websites, the server responses are generally HTML pages or JSON data as common response formats. If you are clear with this blog, the next evident step should be to return HTTP responses in common data formats that are similar to the ones we encounter while surfing the web.

Also, if you are interested in learning web development and start your journey in technology as a web developer, we have a professional web development course curated just for you.

The course that we are talking about is the Konfinity’s Web Development Course The course is well-researched and is one of the most beneficial training courses out there. It is developed by experts from IIT DELHI in collaboration with tech companies like Google, Amazon and Microsoft. It is trusted by students and graduates from IIT, DTU, NIT, Amity, DU and more.

We encourage technocrats like you to join the course to master the art of creating web applications by learning the latest technologies, right from basic HTML to advanced and dynamic websites, in just a span of a few months.

Konfinity is a great platform for launching a lucrative tech career. We will get you started by helping you get placed in a high paying job. One amazing thing about our course is that no prior coding experience is required to take up our courses. Start your free trial here.

Chat with us