Node.js, here I come
- Aryan Tah
- Dec 13, 2022
- 2 min read

Now that we know what Node.js is, let's try to create a simple web server using it. Now, wait! What's a web server?! In simple words, a web server is a software that serves your website and is used to send requests and get back responses accordingly.It acts as an interface between the browser and web files. It is used to transfer, process and deliver the requested web page on the website.
Node.js makes it easy to create web servers, let's learn how to make one. Firstly, create a new file and save it with the file extension .js. Then copy the code given below and paste it into your editor.
const ht =require('http');
const port =3000;
const host='localhost';
const server = http.createServer((req, res)=>{
res.end('Hello World');});
server.listen(port, hostname,()=>{
console.log(`Server is online, running at http://${host}:${port}/`);
});Now let's try to understand the code line by line. In the first line, we declared a constant named http which is a module which a built-in module in Node.js which allows the creation of an HTTP(HyperText Transfer Protocol) server that listens to the port provided and responds to requests made. We then declare a port where the web server would run.
The host is declared with the unique private address 'localhost' which stands for the local computer that is being used to run the program. The localhost can only be accessed by the local machine and isn't available on the internet. We can use any domain name or IP Address if we want to but for now, we would be running the server locally on the machine.
Next, we create a server with the .createServer function method that creates an HTTP server which listens to the port provided and handles requests coming from the user end. It has two parameters which stands for Request and Response.
We end the response using res.end method by providing the text 'Hello World' which is displayed in the form of HTML. We then assign the server to a port by using the server.listen()
In order to run the program, open the file in the terminal and use the command line:
node server.jsIf the console prints the 'Server is online' message, that means that your server is running and it can be accessed from any web browser and has the domain http://localhost:3000
The server will be online until and unless the terminal is operating.

Thanks for reading and if you have any doubts, feel free to contact me using my email address.



Comments