Sunday, 15 April 2012

Routing using director in Node


Director is a URL router module which comes as part of the flatiron framework.  It works in a browser for single page apps and in Node.js. It's not a plugin for another framework. It's not dependent on anything. It's a modern router that was designed from the ground up with javascript.
Installing flatiron
You can install flatiron using npm (npm install flatiron –g)

Director handles routing for HTTP requests similar to journey or express:
var http = require('http');
var director = require(../lib/director');

function sayWelcome(route) {
    this.res.writeHead(200, { 'Content-Type': 'text/plain' });
    this.res.end('Welcome to flatiron routing sample');
}

var router = new director.http.Router({
    '': {
        get: sayWelcome
    }
});

router.get('/index', sayWelcome);
router.get('/home', sayWelcome);

var server = http.createServer(function (req, res) {
    router.dispatch(req, res, function (err) {
        if (err) {
            res.writeHead(404);
            res.end('Error!!!');
        }
    })
});

server.listen(8083);
When developing large client-side or server-side applications it is not always possible to define routes in one location. Usually individual decoupled components register their own routes with the application router. Director supports ad-hoc routing also.
router.path(/\/customers\/(\w+)/, function (res) {
    this.post(function (id) {
        //sayWelcome('some');
        this.res.writeHead(200, { 'Content-Type': 'text/plain' });
        this.res.end('Create a customer with Id = ' + id)
    });

    this.get(function (id) {
        //sayWelcome('some');
        this.res.writeHead(200, { 'Content-Type': 'text/plain' });
        this.res.end('Gets a customer with Id = ' + id)
    });
    this.get(/\/orders/, function (id) {
        this.res.writeHead(200, { 'Content-Type': 'text/plain' });
        this.res.end('Gets orders for a customer with Id = ' + id)
    });
});















No comments:

Post a Comment