Once you have downloaded and installed Node.js on your computer. Now, you are all set to proceed for the next step. i.e. running your first “Hello World” application using Node.js. You are quite excited right? Let us get started with it. If you want to know why you should start learning Node.js right away, here is a small article for you.
First of all, create a Node.js file with name helloworld.js with the code:
You can name it anything you want, but to make you understand, I have given the helloworld.js name over here.
- In the second line of code, we are creating a server application which is based on a simple function. This function is called, whenever you make a request to your server application.
- The writeHead function sends the header data to the client, when the end function will close the connection to the client.
- The listen function makes our server application to listen to a particular port number. In our case, it is 8080.
Executing the Code
Save the file on your computer and note down the entire path.
In the Terminal (command prompt in case of Windows users), navigate to the folder containing the js file.
Run the command
Now, your computer works as a server. Navigate to localhost:8080 if the server is working perfectly or not. It will look similar to the image bellow.