Sunday, 25 September 2016

Getting started with node.js

Node.js – is server-side JavaScript.Node.js is an open source Javascript runtime environment for easily building server-side and networking applications. The platform runs on Linux, OS X, FreeBSD, and Windows, and its applications are written in JavaScript. Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent.

Getting started with node.js

Features of Node.js:
  • Asynchronous and Event Driven.
  • Very Fast.
  • Single Threaded but Highly Scalable.
  • No Buffering.
So in this tutorial i will teach you how to say hello using nodeJS.


Update your package using
sudo apt-get update

Then use apt-get to install the git package, which npm depends on:
sudo apt-get install git

cd ~

Now extract the tar archive you just downloaded into the node directory with these commands:
mkdir node
tar xvf node-v*.tar.?z --strip-components=1 -C ./node

If you want to delete the Node.js archive that you downloaded, since we no longer need it. Then
cd ~
rm -rf node-v*

For globle prefix configuation
mkdir node/etc
echo 'prefix=/usr/local' > node/etc/npmrc

Now we're ready to move the node and npm binaries to our installation location.
sudo mv node /opt/

For changing the permission of root user.
sudo chown -R root: /opt/node

Create a symlinks:
sudo ln -s /opt/node/bin/node /usr/local/bin/node
sudo ln -s /opt/node/bin/npm /usr/local/bin/npm

Verify the node is installed using command.
node -v

Create a new file inside our node folder and name it  server.js. Open this file in your favorite editor and add the below piece of code.
var http = require("http"),
port = 8000;  
var server = http.createServer(function(request,response){  
response.writeHeader(200, {"Content-Type": "text/plain"});  
response.write("Hello HTTP!");  
console.log("Server Running on "+port+".\nLaunch http://localhost:"+port);

Yes, that’s it. This is our HTTP server, that will understand all the HTTP requests and can respond accordingly.

In this code we simply load module system and specify the port which we are using for the app.Creates a new Server and this function takes a callback. Remember everything in Node is Async!. The anonymous function takes in the request and response object. 

Now back to the console and run.
node server.js

Open a browser and navigate to http://localhost:8000/  and there you can see your message!

This is just a simple handshake with the nodeJS but we can do a lot more with nodeJS. In future i will share more post on nodeJS.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts