Nodejs Hello World Example

By

Now , that you know what is NodeJS in previous post , lets start by writing a Hello World Program in NodeJS . In order to write NodeJS Hello World Program , you need to have NodeJS installed in your system . Have a look at this guide .

Once you have installed Nodejs stable version , lets go ahead and follow steps

Create a Directory for Nodejs application

Navigate to any of the hard drive location and follow the steps

mkdir frugalisapp
cd frugalisapp

This step is simple and should be done irrespective of the operating system . This is the folder where you are going to do your stuff and its the project directory . Before going you need to initialize Npm in Project Directory .

Initialize NPM in Project Directory

You can read more about npm here , But in short NPM is a package manager in NodeJS like maven in Java World. Npm is the place where all packages reside .Packages can be thought as bundles of code or modules, which carry out a specific task .

Lets run following command on console

npm init

It download’s the application dependency from npm global repository .

Follow the Steps and enter required info or Just keep on Pressing enter 🙂 .So now a package.json will be created which is responsible for handling all project dependencies . So now we are all set to start coding .

Import http Library

Create a file named myServer.js inside your working directory . We are going to import http library and store the instance in a constant variable . We are going to use the instance to create a server and listen on our desired port.

const httpServer= require('http')

Create NodeJS Server

We now need to create a Nodejs server which will listen to specific mentioned port .


const httpServer= require(‘http’);

const hostname = ‘localhost’;

const port = 8084;

const server = httpServer.createServer((req, res) => {

 res.statusCode = 200;

 res.end(‘<html><body><h1>Hello World to , Nodejs Lovers !!</h1></body></html>’);
})

server.listen(port, hostname);

console.log("Nodejs Tutorials - http://localhost:%d", port);
  • httpServer.createServer – creates a http server which takes up two arguments request (req) and response(res) .
  • res.statusCode=200 it sends standard http response with status code as 200 .
  • res.end() – It actually ends the response process with whatever argument you pass in parameter . Default content type is Html we can also send a JSON response and end the response thread with res.end() .But in that case we need to set the JSON as content type.

Execute and run above code in command line

node myServer.js

This starts server at http://localhost:8084 , navigate to the link in your browser and you will be able to see the Hello World message .

Happy Learning ………………………..

Learn REST API Using Nodejs