Tuesday, 27 September 2016

Nodejs Environment Setup in Windows

Getting Nodejs:

We will focus on following :

  • Install and setup node.js on windows.
  • Run a “Hello world!”-program.
  • Create a webserver program.

Installation:

Nodejs can be downloaded from https://nodejs.org/en/download/ . Here choose for windows installer for 32 and 64 bit OS. Choose the Current version or most recommended version. When download finishes , go to .msi installer and install it . Now you are done with the installation.
Go and open windows search menu and type nodejs to open nodejs console and type the first command 

> node
and you will be prompted to node console and can access all its functionalities.

Runnig A 'Hello World' program:

After opening console , now lets create a js file . Lets say it index.js and enter the following into this js file.


console.log("Hello World");
    and save it .
Now lets open the Nodejs console and browse to index.js file .
and simply type 

> node index.js


and it will output 

Hello World

in the console.


Create a webserver program:

Now we can use the program we encountered in the Introduction .

Copy this code Snippet into your index.js 
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

and run again the command
> node index.js

you will see a message in the console as 


> Server running at http://127.0.0.1:3000


now open your browser and go to url mentioned in the above program.
i.e.  http://127.0.0.1:3000 .
and you wil see 'Hello World'.



Congreates !! you have successfully made an http connection .

In the next  section we will understand nodejs architecture.

1 comment: