Aug 4, 2021

2 min read

What is a Web Server? and How to create a simple Web Server in Node.js?

Web server simply stores the files and data and serve them on request by the client. To open our browser says Google Chrome and type our query, that query is converted into an HTTP request and this request is sent to a dedicated web server. But web server stores huge data and our searched query is fetched out and sent back to our browser which is called HTTP response. The below picture shows the above-discussed structure.

How To Create a Simple Web Server?

In order to build our server in Node.js, we have to do two things.

1. First we create the server.

2. Then we start the server listen to incoming requests.

1. In the above code there are two variables one requests (req) and another is response(res). HTTP (HyperText Transfer Protocol) is Node.js built-in the module by requiring it we can handle all the requests and responses. .creatServer is a method included in the HTTP module. And the callback function holds the response.

Each time the new request hits our server callback function will get called, and the callback function will have access to the request object which holds all kinds of stuff like the request URL and more. On the other hand response object gives us a lot of tools basically to dealing with response. And here we used the simplest one which is .end.

2. Creating a server was the first part, now the second part is actually listening to incoming requests from the client. Saved the results of created server in a variable named as Server. Now we use this newly created variable to listen to requests. Here 8000 in code is actually a port number. And ‘’ is an IP of the current computer, it is optional to define. It may also be referred as standard IP. (Internet Protocol)