In this tutorial you will learn about the NodeJs Hello World Application and its application with practical example.
Node Js Hello World Application
We will start learning Node Js application development by creating a “Hello world!” application. The “Hello world!” program is a simple yet complete example for beginners that illustrates the basics of Node Js. The “Hello world!” application will also gives you a way to test systems and development environment. This tutorial will guide you through writing a basic “Hello World!” application in Node Js.
In order to start with this tutorial, you will need NodeJS and NPM installed, so if you don’t have it installed, follow Nodejs Installation to have it installed.
This nodejs example will print “Hello World!” message on http://localhost:3000.
Step 1:- Let’s create a project folder as “nodeapp “application and switch to that project directory.
1 2 |
$ mkdir nodeapp $ cd nodeapp |
Step 2:- Now, run the following command to initialize the node.js application –
1 |
$ npm init |
It will prompt for some inputs and will create a package.json file , this file is created to define all of the required modules and dependencies which is going to be used for this project.
here, we have defined index.js as the entry point file –
Step 3:- Let’s create index.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 |
var http = require('http'); //Create a server http.createServer(function (req, res) { res.write('Hello World!'); //write a response to the browser res.end(); //end the response }).listen(8080); //the server object listens on port 8080 console.log('Server started'); |
Step 4:- Let’s open the terminal again, change directory to your project folder and type the following command in order to run the server.
1 |
$ node index.js |
Step 5:- Now open the following URL in browser to view the output
http://localhost:8080
Step 6:- You will see the following screen.