Wednesday 13 March 2013

Using Jade with ExpressJs for node.Js

This post will give you a very basic information about usage of Jade with Express framework for node.js. After giving a brief introduction about Jade and what it offers we will design a simple page using some of the cool features of Jade. 

What is Jade 

Jade is a high performance template engine for node.js. It offers a wide variety of features to us. --> Jade

What it offers

The default template in ExpressJs is Jade. Jade offers a great alternative to raw Html. The Jade code which we write will inturn be converted to Html by the engine. Some of the cool features in offer include ,


  • Html tags can be avoided.
                 <html>
                      <head>
                         <title>
                                Jade Introduction
                         </title>
                      </head>
                      <body>
                      </body>
                  </html>

              Can be done using,

                   html
                     head
                       title Jade Introduction
                     body 

        How Cool is that !! 
  • Helps us add dynamic content to a page. Objects can be passed to a Jade page which can then be iterated through to display the content. Among the features are Switch Case, Each (for loop) and mixins. Jade Github Page gives you the whole bunch of features that are available in Jade. We will implement some of them.
A Jade Page using Switch and Each 

  • Go to some folder of your liking and type out the following to create a base version of the app.
          express --session --css stylus jadeintro

          This creates our app with sessions enabled, using stylus for css and using Jade. And ofcourse you could see  our app folder as jadeintro.

  • The next step would be to install the dependencies. Get into the folder jadeintro and type out npm install. 
          cd jadeintro
          npm install 
  • You could see that in views/ directory, there are two Jade files. One would be layout.jade and other would be index.jade. Layout contains the main layout of the page that index is going to use. 
  • You could see already that a value is passed to the Jade page that is being displayed as #{title} in index.jade
  • In app.js by default / is directed to routes.index. That is index function exported in index.js file. 
                   app.get('/', routes.index);
           The line says to call routes.index function when a get request for the root page is received. In index exported at index.js file we see just a single line ,

                   res.render('index', { title: 'Express' });
              res.render is calling index , which would call index.jade and it is passed an object title. This title is going to be used in index.jade page.

  • Lets pass something other than the simple title object that is being passed. Lets pass an object which contains a list which we will display in our page.
                    exports.index = function(req, res){
              var obj1 = {
                        key : 'Point 1',
        value : ' Jade is Awesome '
              };
              var obj2 = {
          key : 'Point 2 ',
        value :' Jade is cool '
              };
             var arr = [] ;
             arr.push(obj1);
             arr.push(obj2);
                     res.render('index', {title: 'Express', data: arr});
                  };

  • Lets now modify the index.jade file to print the stuff we just passed to it.
                   extends layout

                   block content
             h1= title
             p Welcome to #{title}
             ul
       each item in data
         li #{item.key} ------------- #{item.value} 
Easily done. Output looks something like this in my chrome browser.



    Well that ends out Jade introduction. Just a quick reminder on how Jade works. Its based on indentation. You can use either spaces or tabs and not both. Mostly we use tabs and its a bit easier that way. But by default it would be using spaces. Change accordingly. Have fun trying out Jade now!! 

Tuesday 12 March 2013

Node.js - A Sample App

I do realize the best way to move forward now is to start creating an app. We learn loads of stuff when we start trying out stuff.

The name of our app is TaskManager. App primarily has two pages .


  • A Login Page 
  • Home Page
Login Page is the starting page of the website and after login user will be redirected to his home page.


Home page will have options to

  • Add a New Task
  • List the Tasks of the user
A sneak peak on how the login screen will look like once we are done,



Prerequisites

  1. Nodejs installed
  2. Express package added
  3. mongodb installed.
  4. A Teeny tiny intro to jade 
  5. And a beginner level intro to stylus
After getting Hello World ready using the way we did in last post, we can now go ahead and start doing the fancy stuff. 

Jade

Jade is a really gud alternative to using html in our code. Apart from giving the basic stuff as in html, Jade can also help add dynamic stuff to the page(which we ll see in our app) . Jade Help

Stylus

Stylus is an alternative to css stylesheet. There is a compiler which inturn converts our stylus code to .css file. An easy alternative to css. 

Mongodb

Mongodb is the database that we are going to use. A very basic introduction to mongodb can be found here

Database Design

Lets create a database in mongodb using ,

                use taskmanager 

Create two collections users and tasks. users will have the information about our users for authentication and tasks , the tasks. 

               db.users.insert({uname:"sherlock" , password:"pass"})

This will create first user entry in db. The structure of tasks is going to be 

              db.tasks.insert({uname:"sherlock", date: "12-03-2013", desc: "desc"})

Exporting index.js : 
  • Now lets get into adding code to perform task whn we enter home page.
  • In app.js add the following 
    •  app.get('/', routes.index) 
      That will call export.index in the routes file where we can handle what needs to be done with our home page.
             exports.index = function (req, res) {
         res.render('index', {title : ""})
             };
      This will inturn render index.jade file. Jade file and its contents can be found in the github code. Please follow it from there. 
       
             Taskmanager Code

      Well we have added code in jade to add the signup button with username and password textboxes added. Now we need to handle what needs to be done when signup is clicked.

     We will add code in app.js to handle post to /signup page.

             app.post('/signup', routes.signup)

     If you take a peak at whats in code from the github link provided you will find that we have processed the  form data passed to signup and checked Db to find if the user is valid .
     If the user details has passed the Authentication test we redirect the user to home page.


Home Page:

   I have not mentioned much about the stylesheet and jade codes for the index page. If you take a peak at the code, you will be able to understand the straightforward code.

   Home page is where we do the core functionality. We provide an option to user to add tasks and we also display the set of tasks added by user. Again a sneak peak at what the output will look like.


There are some sweet code added in home.jade which needs to be highlighted. A cute little feature of jade is that objects can be passed to the jade code. If you take a look at the home.jade code we will see that it uses  the objects that are passed to it and prints the same. 

Using loops in jade

It was a wow moment when i realised that i can loop in jade and print stuff just like you would embed html within php loops. It is used in home.jade code where we pass the objects to jade code. There we use a loop and print all tasks which is how we add the tasks that are in right side of page.

                     block rightcontent
             .widget
      h2 Saved Tasks
      ul
each item in data
li #{item.date} - #{item.desc} <hr/>


A Cool and simple Hack 

Ajax is not being used in this code to avoid complexity for this sample simple website. But when we add task  in the home page we see it immediately without having to refresh manually ( refresh does take place tho) .

We pass the task information to "/posttask" . Code for that is in user.js where you would see this code,
                   
        exports.posttask = function(req, res) {
var databaseUrl = "taskmanager"; // "username:password@example.com/mydb"
var collections = ["users", "tasks"];
var db = require("mongojs").connect(databaseUrl, collections);
// add the task to db and redirect to the /home page . the task list will be updated by then
AddToDb(req, res);
}

Add to db adds stuff to db and redirects us to home page. If you see the home page code, we get tasks from db before displaying them and therefore we have them neatly updated. This sums up our sample app to create the Taskmanager app.

There are loads of stuff from code which i haven't mentioned here. Please take a look at them from the code base in github. TaskManager code . I wouldn't want to make this post any longer. If you dont get the this working you may ask your questions in comments. Hit +1 if you find this useful. Have fun coding !!


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. 

Tuesday 25 September 2012

Billboards - Interviewstreet Problem

This is my first post of possibly a series about my attempts to solve some of the Interview Street Problems. Am a beginner and hence its going to take a lot of learning to solve some of these problems.

Its evident that the right solution is not that solves the problem but the one that solves it efficiently ! ;) Well tht aint easy. 

For this particular problem one of the approach suggested was to use Dynamic Programming. Heres a really gud tutorial for an intro on wht that is . 

For this particular problem tho, tht algo has to be tweaked. 

The base algo that I used is this, 
n,k are no. of positions and k is the grouping limit.
K(j,i){
if(j==n)
  return 0;
else
     if(i==k)
        return Knapsack(j+1,0)  // which means ignore the current position cause a blank space is madatory
     else
        return max( Knapsack(j+1,i) , v[j] + Knapsack(j+1,i+1))  // case where current elem is chosen and case where its not 
}


Well thts the Base Algorithm. Using this algo as such solves 4/10 cases.. Jump of 1000 Rank (Worth it !!) 

Now am looking for a efficient optimization of this algo to reduce the running cause the rest of the testcases give a time limit exceeded error ( Inefficient Algo used )  .  Any help would be appreciated btw :)


Made some progress on this one. Implemented Dynamic programming iterative way which solved 7 of the 10 cases. Way too easy than my previous approach.

Took reference from this post in stackoverflow http://stackoverflow.com/questions/9376976/removal-of-billboards-from-given-ones .

Made an optimization to use only two rows and re use it instead of assigning memory for n rows. Efficient usage of memory which avoid Core Dump Problem. (Idea from a post in Topcoder) . Now 3 testcases give me a time limit exceeded error. Will work on them now.