In this blog post we will see how to begin with nodejs and writing your first application
Installation
Installing nodejs is quite easy, on windows directly download the the msi installed from http://nodejs.org/download/
On Ubuntu, use your package manager
[code]
$ curl -sL https://deb.nodesource.com/setup | sudo bash -
$ sudo apt-get install -y nodejs
$ apt-get install -y build-essential
[/code]
on centos
[code]
$ curl -sL https://rpm.nodesource.com/setup | bash -
$ yum install -y nodejs
$ yum install gcc-c++ make
[/code]
Only nodejs is installed write
[code]
$ node -v
[/code]
on your command line and it should print out the version number. This means nodejs has been installed properly.
Your First NodeJS Application
Open your text edit and write
console.log('Hello World!'); //print on screen
process.exit(0); //exist the application
save the files as first.js
Next run
[code]
$ node first.js
[/code]
This should output Hello World!, on your screen.
Nodejs is capable of running full javascript, so all if condition, for loops, variable same as javascript will work.
Another simple code would be
console.log('Start…');
var i = 0;
for(i=0;i<20;i++){
console.log(i);
}
NPM - Nodejs Package Manager
NPM is a nodejs command line tool which is used to install various libraries which are required by nodejs.
Install a module is very easy
[code]
npm install [packagename]
e.g
$ npm install async
[/code]
The above installs async package.
Experiments
-
Write a code display current date in nodejs.
-
Define a JSON Object and write a for loop display it.