Pages

Tuesday, December 17, 2013

A newbie's path to web application development using node.js


Javascript have always amazed me. It has a unique talent of doing complex things in a very easy manner, proved by the amazing jQuery. Some time ago, I had struggled to do pretty much everything related to web and mobile app development, but javascript have done me a lot of help. I used jQuery mobile with Phonegap to build my small android applications with considerable less amount of time compared to what I used to take when I was using its traditional coding way. Occasionally, I also had to create some backend web applications for my mobile app to communicate, for which I studied some basics of J2EE Servlets. My applications needed only the basic things, just a web server to communicate with and do some database operations. Presently, a friend of mine asked me to help him out with his academic project and was looking forward on creating another web app backend with J2EE, I stumbled upon node.js. I knew it could do what I want and better with a lot less effort. So I thought I would give it a try, and here I am blogging as I study more about node.js



I installed node.js with NVM on an Ubuntu VPS that I have on digitalocean, and the digitalocean tutorial on how to install node.js served me well. So I dont think I need to repeat that again here, you can have a look at it here. NVM is Node Version Manager, just something that allows you to choose which version of node.js you want to use. So don't set your mind too much on that. For testing and studying node.js you can install it on your system itself.

The basic and first thing that I learned about is how to make a web server and make it listen to a specific port for incoming web request, and respond to it. Too much, huh! The code is :
var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Yes Boss! Thats it!");
  response.end();
}).listen(9090);

Open a text editor and type in this code, save it as somefile.js. Open up you command prompt or terminal or whatever, go to the directory where you just save the file and type in "node somefile.js" (without the quotes,ofcourse), go to http://localhost:9090/ (use ip instead of localhost if hosting on a webserver) from your browser and you can see "Yes Boss! Thats it!" printed on your screen. Voila! We have just created a web server, made it listen to incoming requests on port 9090, accept a request and sent in a reply. That all done in 6 lines of code. Thats why I love node.js!

On the upcoming days, I will write more on node.js, so stay tuned or look up and read all these resources on other sites if you are so much excited.
Official Website

Thank you for reading my blog! Please do comment!




1 comment: