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.

Installation:

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 ~
wget https://nodejs.org/dist/v4.2.3/node-v4.2.3-linux-x64.tar.gz

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!");  
response.end();  
});
server.listen(port);  
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.


No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular