a tiny and isomorphic URL router for JavaScript
Director is a router. Routing is the process of determining what code to run when a URL is requested.
A routing library that works in both the browser and node.js environments with as few differences as possible. Simplifies the development of Single Page Apps and Node.js applications. Dependency free (doesn't require jQuery or Express, etc).
Run the provided CLI script.
./bin/build
It simply watches the hash of the URL to determine what to do, for example:
http://foo.com/#/bar
Client-side routing (aka hash-routing) allows you to specify some information about the state of the application using the URL. So that when the user visits a specific URL, the application can be transformed accordingly.
Here is a simple example:
<meta charset="utf-8"> <title>A Gentle Introduction</title> <script src="https://rawgit.com/flatiron/director/master/build/director.min.js"> </script> <script> var author = function () { console.log("author"); }; var books = function () { console.log("books"); }; var viewBook = function (bookId) { console.log("viewBook: bookId is populated: " + bookId); }; var routes = { '/author': author, '/books': [books, function() { console.log("An inline route handler."); }], '/books/view/:bookId': viewBook }; var router = Router(routes); router.init(); </script> </pre><ul> <li><a href="https://github.com/flatiron/director/blob/master/#/author">#/author</a></li> <li><a href="https://github.com/flatiron/director/blob/master/#/books">#/books</a></li> <li><a href="https://github.com/flatiron/director/blob/master/#/books/view/1">#/books/view/1</a></li> </ul>
Director works great with your favorite DOM library, such as jQuery.
<meta charset="utf-8"> <title>A Gentle Introduction 2</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <script src="https://rawgit.com/flatiron/director/master/build/director.min.js"> </script> <script> $('document').ready(function() { // // create some functions to be executed when // the correct route is issued by the user. // var showAuthorInfo = function () { console.log("showAuthorInfo"); }; var listBooks = function () { console.log("listBooks"); }; var allroutes = function() { var route = window.location.hash.slice(2); var sections = $('section'); var section; section = sections.filter('[data-route=' + route + ']'); if (section.length) { sections.hide(250); section.show(250); } }; // // define the routing table. // var routes = { '/author': showAuthorInfo, '/books': listBooks }; // // instantiate the router. // var router = Router(routes); // // a global configuration setting. // router.configure({ on: allroutes }); router.init(); }); </script> <section data-route="author">Author Name</section> <section data-route="books">Book1, Book2, Book3</section> </pre><ul> <li><a href="https://github.com/flatiron/director/blob/master/#/author">#/author</a></li> <li><a href="https://github.com/flatiron/director/blob/master/#/books">#/books</a></li> </ul>
You can find a browser-specific build of
directorhere which has all of the server code stripped away.Server-Side HTTP Routing
Director handles routing for HTTP requests similar to
journeyorexpress:// // require the native http module, as well as director. // var http = require('http'), director = require('director');// // create some logic to be routed to. // function helloWorld() { this.res.writeHead(200, { 'Content-Type': 'text/plain' }) this.res.end('hello world'); }
// // define a routing table. // var router = new director.http.Router({ '/hello': { get: helloWorld } });
// // setup a server and when there is a request, dispatch the // route that was requested in the request object. // var server = http.createServer(function (req, res) { router.dispatch(req, res, function (err) { if (err) { res.writeHead(404); res.end(); } }); });
// // You can also do ad-hoc routing, similar to
journey
orexpress
. // This can be done with a string or a regexp. // router.get('/bonjour', helloWorld); router.get(/hola/, helloWorld);// // set the server to listen on port
8080
. // server.listen(8080);See Also:
Director supports Command Line Interface routing. Routes for cli options are based on command line input (i.e.
process.argv) instead of a URL.
var director = require('director');var router = new director.cli.Router();
router.on('create', function () { console.log('create something'); });
router.on(/destroy/, function () { console.log('destroy something'); });
// You will need to dispatch the cli arguments yourself router.dispatch('on', process.argv.slice(2).join(' '));
Using the cli router, you can dispatch commands by passing them as a string. For example, if this example is in a file called
foo.js:
$ node foo.js create create something $ node foo.js destroy destroy something
this
var router = Router(routes);
An object literal that contains nested route definitions. A potentially nested set of key/value pairs. The keys in the object literal represent each potential part of the URL. The values in the object literal contain references to the functions that should be associated with them. bark and meow are two functions that you have defined in your code.
// // Assign routes to an object literal. // var routes = { // // a route which assigns the function `bark`. // '/dog': bark, // // a route which assigns the functions `meow` and `scratch`. // '/cat': [meow, scratch] };// // Instantiate the router. // var router = Router(routes);
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. We refer to this as Adhoc Routing. Lets take a look at the API
directorexposes for adhoc routing:
Client-side Routing
var router = new Router().init();router.on('/some/resource', function () { // // Do something on
/#/some/resource
// });
HTTP Routing
var router = new director.http.Router();router.get(//some/resource/, function () { // // Do something on an GET to
/some/resource
// });
In large web appliations, both Client-side and Server-side, routes are often scoped within a few individual resources. Director exposes a simple way to do this for Adhoc Routing scenarios:
var router = new director.http.Router();// // Create routes inside the
/users
scope. // router.path(//users/(\w+)/, function () { // // Thethis
context of the function passed to.path()
// is the Router itself. //this.post(function (id) { // // Create the user with the specified `id`. // }); this.get(function (id) { // // Retreive the user with the specified `id`. // }); this.get(/\/friends/, function (id) { // // Get the friends for the user with the specified `id`. // });
});
In
director, a "routing event" is a named property in the Routing Table which can be assigned to a function or an Array of functions to be called when a route is matched in a call to
router.dispatch().
onmethod(s).
Client-side only
Given the flexible nature of
directorthere are several options available for both the Client-side and Server-side. These options can be set using the
.configure()method:
var router = new director.Router(routes).configure(options);
The
optionsare:
forward,
backward, or
false. Default is
falseClient-side, and
backwardServer-side.
false, then trailing slashes (or other delimiters) are allowed in routes. Default is
true.
trueor
false. Default is
false.
/.
router.dispatch().
router.dispatch()when a route is found.
router.dispatch()when a route is found.
Client-side only
trueand client supports
pushState(), then uses HTML5 History API instead of hash fragments. See History API for more information.
html5historyis enabled, the route handler by default is executed upon
Router.init()since with real URIs the router can not know if it should call a route handler or not. Setting this to
falsedisables the route handler initial execution.
html5historyis enabled, the window.location hash by default is converted to a route upon
Router.init()since with canonical URIs the router can not know if it should convert the hash to a route or not. Setting this to
falsedisables the hash conversion on router initialisation.
var router = Router({ // // given the route '/dog/yella'. // '/dog': { '/:color': { // // this function will return the value 'yella'. // on: function (color) { console.log(color) } } } });
Routes can sometimes become very complex,
simple/:tokensdon't always suffice. Director supports regular expressions inside the route names. The values captured from the regular expressions are passed to your listener function.
var router = Router({ // // given the route '/hello/world'. // '/hello': { '/(\\w+)': { // // this function will return the value 'world'. // on: function (who) { console.log(who) } } } });
var router = Router({ // // given the route '/hello/world/johny/appleseed'. // '/hello': { '/world/?([^\/]*)\/([^\/]*)/?': function (a, b) { console.log(a, b); } } });
When you are using the same route fragments it is more descriptive to define these fragments by name and then use them in your Routing Table or Adhoc Routes. Consider a simple example where a
userIdis used repeatedly.
// // Create a router. This could also be director.cli.Router() or // director.http.Router(). // var router = new director.Router();// // A route could be defined using the
userId
explicitly. // router.on(/([\w-_]+)/, function (userId) { });// // Define a shorthand for this fragment called
userId
. // router.param('userId', /([\w\-]+)/);// // Now multiple routes can be defined with the same // regular expression. // router.on('/anything/:userId', function (userId) { }); router.on('/something-else/:userId', function (userId) { });
It is possible to define wildcard routes, so that /foo and /foo/a/b/c routes to the same handler, and gets passed
""and
"a/b/c"respectively.
router.on("/foo/?((\w|.)*)"), function (path) { });
Can be assigned the value of
forwardor
backward. The recurse option will determine the order in which to fire the listeners that are associated with your routes. If this option is NOT specified or set to null, then only the listeners associated with an exact match will be fired.
var routes = { '/dog': { '/angry': { // // Only this method will be fired. // on: growl }, on: bark } };var router = Router(routes);
backward, with the URL /dog/angry
var routes = { '/dog': { '/angry': { // // This method will be fired first. // on: growl }, // // This method will be fired second. // on: bark } };var router = Router(routes).configure({ recurse: 'backward' });
forward, with the URL /dog/angry
var routes = { '/dog': { '/angry': { // // This method will be fired second. // on: growl }, // // This method will be fired first. // on: bark } };var router = Router(routes).configure({ recurse: 'forward' });
var routes = { '/dog': { '/angry': { // // This method will be fired first. // on: function() { return false; } }, // // This method will not be fired. // on: bark } };// // This feature works in reverse with recursion set to true. // var router = Router(routes).configure({ recurse: 'backward' });
Before diving into how Director exposes async routing, you should understand Route Recursion. At it's core route recursion is about evaluating a series of functions gathered when traversing the Routing Table.
Normally this series of functions is evaluated synchronously. In async routing, these functions are evaluated asynchronously. Async routing can be extremely useful both on the client-side and the server-side:
The method signatures for route functions in synchronous and asynchronous evaluation are different: async route functions take an additional
next()callback.
var router = new director.Router();router.on('/:foo/:bar/:bazz', function (foo, bar, bazz) { // // Do something asynchronous with
foo
,bar
, andbazz
. // });
var router = new director.http.Router().configure({ async: true });router.on('/:foo/:bar/:bazz', function (foo, bar, bazz, next) { // // Go do something async, and determine that routing should stop // next(false); });
Available on the Client-side only. An object literal containing functions. If a host object is specified, your route definitions can provide string literals that represent the function names inside the host object. A host object can provide the means for better encapsulation and design.
var router = Router({'/hello': { '/usa': 'americas', '/china': 'asia' }
}).configure({ resource: container }).init();
var container = { americas: function() { return true; }, china: function() { return true; } };
Available on the Client-side only. Director supports using HTML5 History API instead of hash fragments for navigation. To use the API, pass
{html5history: true}to
configure(). Use of the API is enabled only if the client supports
pushState().
Using the API gives you cleaner URIs but they come with a cost. Unlike with hash fragments your route URIs must exist. When the client enters a page, say http://foo.com/bar/baz, the web server must respond with something meaningful. Usually this means that your web server checks the URI points to something that, in a sense, exists, and then serves the client the JavaScript application.
If you're after a single-page application you can not use plain old
tags for navigation anymore. When such link is clicked, web browsers try to ask for the resource from server which is not of course desired for a single-page application. Instead you need to use e.g. click handlers and call the
setRoute()method yourself.
this
Available in the http router only. Generally, the
thisobject bound to route handlers, will contain the request in
this.reqand the response in
this.res. One may attach additional properties to
thiswith the
router.attachmethod:
var director = require('director');var router = new director.http.Router().configure(options);
// // Attach properties to
this
// router.attach(function () { this.data = [1,2,3]; });// // Access properties attached to
this
in your routes! // router.get('/hello', function () { this.res.writeHead(200, { 'content-type': 'text/plain' });// // Response will be `[1,2,3]`! // this.res.end(this.data);
});
This API may be used to attach convenience methods to the
thiscontext of route handlers.
When you are performing HTTP routing there are two common scenarios:
Content-Typeheader (usually
application/jsonor
application/x-www-form-urlencoded).
.pipeor listening to the
dataand
endevents.
By default
director.http.Router()will attempt to parse either the
.chunksor
.bodyproperties set on the request parameter passed to
router.dispatch(request, response, callback). The router instance will also wait for the
endevent before firing any routes.
Default Behavior
var director = require('director');var router = new director.http.Router();
router.get('/', function () { // // This will not work, because all of the data // events and the end event have already fired. // this.req.on('data', function (chunk) { console.log(chunk) }); });
In flatiron,
directoris used in conjunction with union which uses a
BufferedStreamproxy to the raw
http.Requestinstance. union will set the
req.chunksproperty for you and director will automatically parse the body. If you wish to perform this buffering yourself directly with
directoryou can use a simple request handler in your http server:
var http = require('http'), director = require('director');var router = new director.http.Router();
var server = http.createServer(function (req, res) { req.chunks = []; req.on('data', function (chunk) { req.chunks.push(chunk.toString()); });
router.dispatch(req, res, function (err) { if (err) { res.writeHead(404); res.end(); } console.log('Served ' + req.url); });
});
router.post('/', function () { this.res.writeHead(200, { 'Content-Type': 'application/json' }) this.res.end(JSON.stringify(this.req.body)); });
Streaming Support
If you wish to get access to the request stream before the
endevent is fired, you can pass the
{ stream: true }options to the route.
var director = require('director');var router = new director.http.Router();
router.get('/', { stream: true }, function () { // // This will work because the route handler is invoked // immediately without waiting for the
end
event. // this.req.on('data', function (chunk) { console.log(chunk); }); });
options{Object}: Options to configure this instance with.
Configures the Router instance with the specified
options. See Configuration for more documentation.
matcher
token.
Adds a route fragment for the given string
tokento the specified regex
matcherto this Router instance. See URL Parameters for more documentation.
method{string}: Method to insert within the Routing Table (e.g.
on,
get, etc.).
path{string}: Path within the Routing Table to set the
routeto.
route{function|Array}: Route handler to invoke for the
methodand
path.
Adds the
routehandler for the specified
methodand
pathwithin the Routing Table.
path{string|Regexp}: Scope within the Routing Table to invoke the
routesFnwithin.
routesFn{function}: Adhoc Routing function with calls to
this.on(),
this.get()etc.
Invokes the
routesFnwithin the scope of the specified
pathfor this Router instance.
Dispatches the route handlers matched within the Routing Table for this instance for the specified
methodand
path.
routesinto.
Inserts the partial Routing Table,
routes, into the Routing Table for this Router instance at the specified
path.
redirect{String}: This value will be used if '/#/' is not found in the URL. (e.g., init('/') will resolve to '/#/', init('foo') will resolve to '/#foo').
Initialize the router, start listening for changes to the URL.
index{Number}: The hash value is divided by forward slashes, each section then has an index, if this is provided, only that section of the route will be returned.
Returns the entire route or just a section of it.
route{String}: Supply a route value, such as
home/stats.
Set the current route.
start{Number} - The position at which to start removing items.
length{Number} - The number of items to remove from the route.
Remove a segment from the current route.
index{Number} - The hash value is divided by forward slashes, each section then has an index.
value{String} - The new value to assign the the position indicated by the first parameter.
Set a segment of the current route.
Is using a Client-side router a problem for SEO? Yes. If advertising is a requirement, you are probably building a "Web Page" and not a "Web Application". Director on the client is meant for script-heavy Web Applications.