• Stars
    star
    319
  • Rank 131,491 (Top 3 %)
  • Language
    JavaScript
  • Created almost 14 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

a minimalist url-style routing library, extracted from connect

Routes.js

routes lets you easily dispatch based on url-style strings. It comes with a default Router function that you can use to route http requests, but it also cleanly exposes the important functionality so you could also use it to perform more generic string pattern matching.

This might make it useful for things like:

  • URI routing
  • Cucumber-style pattern matching :)
  • Routing messages by channel name from an MQ
  • Dispatching hierarchical events by name

Alternative routers.

This module is no longer actively worked on. This module operates just fine as is, however you might want to use a module that is under active maintenance:

Router Example:

The full range of Path Formats is documented below.

var Router = require('routes');
var router = Router();
var noop = function(){};

router.addRoute("/articles/:title?", noop);
router.addRoute("/:controller/:action/:id.:format?", noop);

console.log(router.match("/articles"));
console.log(router.match("/articles/never-gonna-let-you-down"));
console.log(router.match("/posts/show/1.json"));

The output for router.match("/posts/show/1.json") would be:

{
  params: {
    controller: 'posts',
    action: 'show',
    id: '1',
    format: 'json'
  },
  splats: [],
  route: '/:controller/:action/:id.:format?',
  fn: [Function],
  next: [Function]
}

In the example above, fn would be the function that was passed into the router.

I return this object instead of calling your function for you because you will likely want to add additional parameters from the current context to the function invocation. Ex:

var route = router.match("/posts/show/1.json");
route.fn.apply(null, [req, res, route.params, route.splats]);

HTTP Method Example:

Here is a handy trick if you want to perform pattern matching on http methods:

var router = require('routes')();

router.addRoute("GET /articles/:title?", function (req, res, params) {
  // perform some IO...
  res.end('article content goes here...\n');
});
router.addRoute("POST /articles/:title", function (req, res, params) {
  // perform some IO...
  res.setHeader('content-type', 'text/plain');
  res.end('updated ' + params.title + '\n');
});

var http = require('http');
var server = http.createServer(function (req, res) {
 var m = router.match(req.method + ' ' + req.url);
 if (m) m.fn(req, res, m.params);
 else {
  res.statusCode = 404;
  res.end('not found\n');
 }
});
server.listen(5000);

Match Continuation

The object returned by router.match includes a next function you can use to continue matching against subsequent routes. Routes are evaluated in the order they are added to the router, so generally, you would add your most specific routes first and most ambiguous routes last. Using the next function allows you evaluate more ambiguous routes first.

var Router = require('routes');
var router = new Router();

router.addRoute('/admin/*?', auth);
router.addRoute('/admin/users', adminUsers);

http.createServer(function (req, res) {
  var path = url.parse(req.url).pathname;
  var match = router.match(path);
  match.fn(req, res, match);
}).listen(1337)

// authenticate the user and pass them on to
// the next route, or respond with 403.
function auth(req, res, match) {
  if (checkUser(req)) {
    match = match.next();
    if (match) match.fn(req, res, match);
    return;
  }
  res.statusCode = 403;
  res.end()
}

// render the admin.users page
function adminUsers(req, res, match) {
  // send user list
  res.statusCode = 200;
  res.end();
}

Installation

npm install routes

Path Formats

Basic string:

"/articles" will only match routes that == "/articles".

Named parameters:

"/articles/:title" will only match routes like "/articles/hello", but *not* "/articles/".

Optional named parameters:

"/articles/:title?" will match "/articles/hello" AND "/articles/"

Periods before optional parameters are also optional:

"/:n.:f?" will match "/1" and "/1.json"

Splaaaat! :

"/assets/*" will match "/assets/blah/blah/blah.png" and "/assets/".

"/assets/*.*" will match "/assets/1/2/3.js" as splats: ["1/2/3", "js"]

Mix splat with named parameters:

"/account/:id/assets/*" will match "/account/2/assets/folder.png" as params: {id: 2}, splats:["folder.png"]

Named RegExp:

"/lang/:lang([a-z]{2})" will match "/lang/en" but not "/lang/12" or "/lang/eng"

Raw RegExp:

/^\/(\d{2,3}-\d{2,3}-\d{4})\.(\w*)$/ (note no quotes, this is a RegExp, not a string.) will match "/123-22-1234.json". Each match group will be an entry in splats: ["123-22-1234", "json"]

Router API

The Router() that routes exposes has two functions: addRoute and match.

addRoute: takes a path and a fn. Your path can match any of the formats in the "Path Formats" section.

match: takes a String or RegExp and returns an object that contains the named params, splats, route (string that was matched against), the fn handler you passed in with addRoute, and a next function which will run match against subsequent routes.

Library API

match: takes an array of Routes, and a String. It goes through Routes and returns an object for the first Route that matches the String, or undefined if none is found. The returned object contains params, splats, and route. params is an object containing the named matches, splats contains the unnamed globs ("*"), and route contains the original string that was matched against.

pathToRegExp: takes a path string and an empty keys array, returns a RegExp and populates keys with the names of the match groups that the RegExp will match. This is largely an internal function but is provided in case someone wants to make a nifty string -> [RegExp, keys] utility.

Test

Clone the repo, cd to it, and:

make test

Credits

This library is an extraction and re-factor of the connect router middleware. I found that connect-based routing worked reasonably well on the server side, but I wanted to do similar routing based on channel names when using Push-It and possibly for event names when using Evan. So, I extracted the relevant goodness out of the router middleware and presented it here. Big thanks to TJ Holowaychuk for writing the original router middleware.

License

This code is distributed under the MIT license, Copyright Aaron Blohowiak and TJ Holowaychuk 2011.

More Repositories

1

Push-It

JavaScript push server and client, developing real-time web applications should be easy.. now you can do it in js
JavaScript
156
star
2

clutch

Make a USB pedal send one key tap when you press it in and another when you release it
Objective-C
44
star
3

macros

Aan easy way to define a pre-processor chain for your JavaScript source.
JavaScript
28
star
4

EasyStereoWaveFileHeader

A simple C library for writing out 16-bit Int Stereo 44.1khz .wav files
C
20
star
5

restartr

Restart process when files change - reload node.js automatically
JavaScript
18
star
6

evalsha

a hosted redis script site =)
Ruby
12
star
7

Propagate-JS

Reactive programming for JavaScript; less callbacks, better interfaces
JavaScript
10
star
8

shared-views

I want to share server-side templates with the browser
JavaScript
10
star
9

Random-ID

Pure-JS random base64-uri id generation.
JavaScript
9
star
10

JavaScript-datastructures

A collection of datastructures for JavaScript. Intended to be a nice starting point for building just what you need.
JavaScript
7
star
11

inspector_gadget

Inspector Gadget gives insight into the construction, composition and monkeypatching of ruby classes, modules and methods
Ruby
6
star
12

advent-of-code-2022

Rust
6
star
13

bitset

Go
6
star
14

Pearl

Perl's Autovivification for Ruby : complex object creation without initialization.
Ruby
5
star
15

fsproxy

A FUSE-based filesystem proxy with hooks!
Go
5
star
16

easyhash

convenience wrapper for node.js hash module
JavaScript
4
star
17

Twilio-Node

Twilio API bindings for Node.JS
3
star
18

formulate

thin wrapper for formidable, making it a touch more convenient.
JavaScript
3
star
19

DeskSet

Yet Another Asynchronous JS Library
JavaScript
3
star
20

MinimalStyleSheet

2
star
21

ejsrb

embeddedjs with ruby
JavaScript
2
star
22

iOS-Accelerate-Framework-Benchmark

simple app to test the speed increase of the Accelerate framework on iOS
C
2
star
23

Journaling-Hash

Overriding defaults is awesome, but it can be tricky to debug. Journaling-Hash makes it easy to have a configuration object where you can easily track where configuration changes were made.
2
star
24

soundcloud-cli-ruby

Soundcloud Command-Line Interface in Ruby
Ruby
1
star
25

FastTime

Fast ruby binding to `gettimeofday`. Cheaper than Time.now.to_i.
Ruby
1
star
26

advent-of-code-2021

Ruby
1
star
27

yertlejr

Yertle Jr is a Parsing Expression Grammar (PEG) and parser generator
JavaScript
1
star
28

simple-tracing

Simple Tracing for Ruby.
Ruby
1
star
29

gostar

Generics in Go through simple AST manipulation.
1
star
30

Transitive-Bootstrap

bootstrap a new transitive app.
1
star
31

dx-dt

dx-dt
JavaScript
1
star
32

dxdt-web

The front-end web site for dxdt
JavaScript
1
star
33

Realtime-Experiments

JavaScript
1
star
34

Xitive.com

Our Home page
1
star
35

stochastik.xitive.com

Stochastik web site
1
star
36

blog-old

1
star