Home » Node.js20 July 2017

Node.js: Basic Introduction [Beginner Tutorial]

Node.js is an open-source runtime environment, used to build server-side and networking application using Javascript. Generally, Javascript has been used for client-side scripting. However, with Node.js, you can interact with web-server using Javascript. The APIs of Node.js are asynchronous and event-driven which helps in faster code execution.

Here’s the installation instruction for Node.js.

Creating Hello World application using Node.js

Below is the code for a simple hello world application in node.js.

At first, we will be importing a built-in Node.js module named http. A Node.js module is like a Javascript library that provide certain features. require function is used to include/import the module.

After that, we create server using the http module. The server will listen to a particular port. You can provide any port that is available in your computer. That can be like 8080, 8081, 8888, 3000, etc. The server will read the HTTP request and return a response. We will be listening to port 8081.

response.writeHead() function will write the header of the response. And, response.write() function will send the content to the response. response.end() function can also write the body and this will also close the response.

server.js

Now, open terminal/command-prompt and go to the directory where your server.js file is. My server.js file is at /var/www/html/test/nodejs/server.js.

After you are in the directory where the above created server.js file is, then run the following command:

This will print the message in your terminal/command-prompt saying “Server running at port 8081…” like below:

Now, open your browser and type the following in your browser’s address bar:

http://127.0.0.1:8081

Press Enter and you shall be able to see “Hello World” written.

That’s it! You have successfully created a Node.js server. You have created an HTTP request and sent out the response as Hello World.

Hope this helps. Thanks.

Node.js

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed