What is a Web Server ……….?
It is a machine that stores web information and answers to client requests made through the internet. These are also in charge of running several websites from remote locations. When a request is made, these web servers deliver the webpages to the users, and a webpage is a collection of content, photos, videos, and so on that is hosted on a web server. These exchanges will take place through protocols, most notably HTTP (Hyper Text Transfer Protocol) and HTTPS (Highly Secure HTTP).
Prerequisites for beginning with a basic Nodejs program
- For
first practice on this notion, tools like Notepad / Notepad ++ are sufficient,
but in the future, while developing large apps, we will need to use tools like
Visual Studio Code.
- To run a Nodejs program on your system, you must have Nodejs installed, together with the necessary parameters and system settings. To verify the installation,
- è Open command prompt (cmd), type node -v
Creation of a simple Web Server in Nodejs
To start with, open either of your notepad / vscode, and
write the below code
Explanation of the webserver code:-
- 1st line -> The first line is an import statement that consumes the attributes of the http protocol in a variable called http.
- 3rd line -> We are building a web server using the http protocol and assigning it to a server variable using the createServer function. This technique takes a function as a parameter.
We can initialize the functions in a variety of methods, some of which are as follows:
i) Arrow function = (req, res) => {}
ii) ii) Using the function keyword -> function(req, res) {}
(req, res) are the function parameters, the req is used to request information from the server and the res is used to deliver the response to the website.
- 4th line -> Using the res.write method, the message "A Simple Nodejs Programme" is written to the webpage.
- 5th line -> It concludes the response procedure using res.end()
- 7th line -> We are assigning a PORT number to the server in order for it to handle requests and responses. We've set the value to 3000, but you can experiment with different port numbers.
- 8th line -> This is a log message that is often displayed in the terminal when we run the aforementioned webserver program.
Execution of the above program:-
- First save the above code with a file name and .js extension at the end, in a particular location
- Open cmd, and navigate to the above saved file location
- Write node filename.js and then click ENTER, in cmd.