Sunday 17 February 2013

Node.js - Tutorial - Part 2


After a decent intro abt the framework, We are on our way to write the Immortal Hello World code using Node.js.

In our case Hello World would be a web page displaying "Hello world". Unlike languages like Php which has a Apache Server, if we are to use Node.js we need to write our server code too. This means we need to add code to Handle requests and  Route requests. Thankfully it is not as tough as it may sound initially. We will look at it soon.

Lets start with installation. Based on the OS you are using get the Binary and install it from this Link.
There is also this official installation site which you might take a look with help in installation.
 ExpressJs a web framework for Nodejs will make our life easy to work on a project structure using node.js. Its a framework which might come in handy for us. You can get help about using it from here.

ExpressJs link is a bit important to move forward so I will restate a few key points. Create a directory in some place you like and create a package.json file in there as given in the link. Then type out npm install. When this command ends, it creates a set of directories and files which will help you kick start your development. Actually the working version of your project will be created already and all you need to do is to run.

Just like to add a few more points about installation. In the site http://expressjs.com/guide.html there are a series of steps to generate a working app given which we can then modify to our needs. As given create a directory and place a package.json file in it and do "npm install -g express " in there.And then to use express to create an app. "express -c stylus myapp" would create an app with all directories in it.
 If you could follow the steps you would get a working app which you can then run using

node app.js 

and that will start your server. Typically it listens on 3000 port. So you could type out localhost:3000 on your favorite browser and see the results. Yea Awesome ! Now lets see how it works and what is needed to be changed in order to make things work our way.

Well we ran app.js so it has to be the soul. Lets try to understand stuff from it. The official API documentation of ExpressJs is pretty good and it has a lot of info on what is what which I have to explore better. The directory structure is this,

-- public
          | -- Images
          | -- Stylesheets
          | -- Javascripts

Its obvious what they can be used for. They are just placeholders to hold the appropriate files which we can use from code.
-- Routes
This is an interesting one. As we said earlier in Node.js we need to take care of server handling requests and routing requests. To do the second part we are going to make use of this directory. It basically can contain code that will handle various calls. Say in php you have a file names like  main.php and logout.php and process.php which will be called on certain points and which will contain actions to take. Similarly we have Js files to take care of that in route folder. The core of the routing process itself lies in the the app.js which contains which Module to call on what request.

You may see something like this in your app.js


app.get('/', routes.index);
app.get('/users', user.list);


This means to call routes.index on the root path and to call user.list on the /users which is "www.mywebsite.com/users" link.

Rather interesting thing which you might have noticed is the usage of the word Modules. Yep. Here we can create modules which then can be used from other places in code. There are some prepackaged modules which are the ones like "http" and other stuff. Basically Modules are like Libraries in other languages. They make your job easy. And when you write a new module, you include it in your code and call it when needed.

This is what they do in this line in app.js,


var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')  
  , http = require('http')
  , path = require('path');

And app.get('/', routes.index);

Now its time to see what is in routes. If we are to include a file we wrote we use "./filename" in require. So ./routes is a file named index.js in Routes folder in our case. Or it can be routes.js in the main folder. So routes contain the files needed to be called when certain page requests happen. Public contains css and javascript needed by our webpage. And finally App.js is the core.

Will conclude this part with this last detail from App.js file. As I mentioned earlier we need to be able to write code to handle requests in Node.js. That part of the code is


http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

It uses the Http Module and calls CreateServer. The return from that function is an object and listen is a method of that object which will make our server listen to that respective Port. Now its as easy as that to create the server and make it listen to a port with the help of the Http Module ofc!.

We will see more soon.



Saturday 16 February 2013

Node.js - Tutorial - Part 1


Hello folks. This one is going to be a post about Node.js. Am an absolute beginner at this front . This post is just sharing my experiences about what I learnt and will keep updating when i learn new stuff.

The best way to start learning something new in my opinion would be to read an article with some examples given. Work out the same stuff and start experimenting and eventually take up small projects and get even more proficient in the language or the framework. This is me striding in that journey!

Question 1 : What is node.js? Let me google and find stuff about it.

Explanation from the official site :

" Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. "

Lets break it down a bit.
Its built on Chrome's JS runtime(Whtever!).
Its event driven, non blocking I/O model - Wow that's new. What does that mean. I googled a bit more and found out rather interesting stuff about it. Link provides an interesting benchmark result between Node.js and Php. Essentially Node.js is event driven asynchronous in that Server  adds and event to the queue and sends a callback with it and keeps working on other stuff. There is only one thread serving any number of requests from any number of users. The rest of the tasks( the events queued) are accomplished by  threads from a thread pool maintained by node.js. Its like a manager redirecting tasks to N people at his disposal and keep serving thousands of request. The idea is based on the observation that a fair amount of time in server is wasted on serving up I/O requests. As stated in the explanation from the official site its light weight and scalable. Benchmarks in the link  provided proves the same.

Essentially to sum it up : " Its a platform where server side code can be written using Javascript(Wow!) . Its fast and scalable for RT apps. And hopefully its fairly easy to learn!"

Q2 : Ok I got the initial info needed. Now I need to get my hands dirty to try out some stuff.

This is a crucial step. Quite a few steps are involved in this step. Environment setup, knowing the rules of the game and other stuff.

I believe a decent intro to any new language or framework in Web atleast needs the following

  •     To be able to write a Hello World in it. ( Yea right ! Stop kiddin me U say ! )
  •     To be able to post a message from one page to another. (Server side specifics)
  •     To be able to interact with DB to store and retrieve stuff. ( Server side specific)
  •     And to create a simple yet decent app with it.

We will continue the journey in Part 2.