froute - Simple Node.js Routing

froute

froute provides simple, powerful and functional routing for node with expressive template matching. I wrote this in a day, that’s how simple it is (and that includes the awesome logo that I know you want on a t-shirt).

froute

Getting started

Install via npm:

1
npm install froute

Require the module in the usual way:

1
var froute = require("froute");

Using froute

There are essentially 2 or 3 functions you need to use.

Register routes

You register a route using the bind function:

1
2
3
4
var template = "/apples";
// Bind the static route and it's handler
froute.bind(template, handler); // true

You register routes with parameters in the following way (type and size parameters). Any parameters will then be passed to your handler function:

1
2
var template = "/apple/{type}/size/{size}";
froute.bind(template, handler); // true

Unregister routes

You unregister a route using the unbind function:

1
froute.unbind("/apples");

Unbound templates are returned by the unbind function.

Dispatch

When a url comes in, you call dispatch:

1
froute.dispatch("/apple/gala/size/large");

Your handler will then be called if a route template is matched. If there is no template matched, or handler function to call, froute.dispatch will return false (otherwise true).

Full example

A full example illustrating how the handler function works with params:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var template = "/apple/{type}/size/{size}",
resultParams;
var bindResult = froute.bind(template, function(params) {
resultParams = params;
});
froute.dispatch("/apple/gala/size/large");
// assertions
expect(bindResult).toBeTruthy();
expect(dispatchResult).toBeTruthy();
expect(froute.list().length).toEqual(1);
expect(resultParams).toEqual({type:"gala",size:"large"});

Behind the scenes

froute-picker

froute uses the “froute-picker” module for picking parameters from url templates and matching urls to the templates while assigning parameter values. This is an independent node module, full source here. It can also be used in isolation:

Picking parameters from a url template and matching a url to the template

1
2
3
4
5
6
7
8
var template = "/apple/{type}/size/{size}",
picked = picker.pick(template),
matchUrl = picker.match("/apple/gala/size/large");
result = matchUrl(picked);
// assertions
expect(result.type).toEqual("gala");
expect(result.size).toEqual("large");

functional.js

What better way to manipulate and perform operations on collections than with functional.js. Some of the above functions for froute support currying (such as the bind function), happy days.

Issues and contributions

I’m open to pull requests as always, there are lots of advancements that can be made to the froute-picker.

An apple a day

… might keep the doctor away. With froute, you might even lower your blood pressure :)