a blog for those who code

Saturday, 12 July 2014

Crossroads : Router for Nodejs Developers

In this post we will show you how you can use routers in Nodejs and whats the usage of Crossroads for the Nodejs Developers.


In Node the primary use for a router is to extract the information we need from a URI, and after getting that information use that to trigger the right process. In simple terms passing the information from URI to the process which needs it.

Install Crossroad : npm install crossroads

The important methods of crossroad are :

addRoute - a new route pattern listener is defined by this method.
parse - It parses a string and map to appropriate route.
matched.add - It map a route handler to a route match.

Lets look into an example of using Crossroad :

var crossroads = require('crossroads');
var http = require('http');

crossroads.addRoute('/blog/{label}/:year:/:month',funtion(label,year,month) {
     if(!month && !year) {
console.log('Showing all entries of label ' + label);
return;
     } else if(!month) {
console.log('Showing all entries of label ' + label + ' in year ' + year);
return;
     } else {
console.log('Showing all entries of label ' + label + ' in year ' + year + 'in month ' + month);
     }
});

http.createServer(function(req,res)) {
    crossroads.parse(req.url);
    res.end('Thats all\n');
}).listen(8124);

The following requests :

http://codingdefined.com:8124/label/nodejs
http://codingdefined.com:8124/label/nodejs/2014
http://codingdefined.com:8124/label/nodejs/2014/07

Will generate the following console messages :

Showing all entries of label nodejs
Showing all entries of label nodejs in year 2014
Showing all entries of label nodejs in year 2014 in month 07

Routing can be used with database access, to generate the returned page content. It can also be used with some software or framework in order to process incoming requests.

Please Like and Share the Blog, if you find it interesting and helpful.

1 comment:

  1. Hey i really liked your blog... very simple and direct approach. Thank you very much.

    ReplyDelete

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License