can-route

A simple regexp router that runs inside a `http.createServer` handler and returns false when it can’t route a request.

npm install can-route
26 downloads in the last week
46 downloads in the last month

can-route

can-route is a simple router that runs inside a http.createServer handler and returns false when it can’t route a request. Its routes are defined with named regular expressions.

Build status

Browser support

Install

npm install can-route

Example

var http = require('http')
var can = require('can-route')()

// Home
can.get(/^\/$/,
  function(req, res) {
    res.end('Welcome to the homepage\n')
  }
)

// Item
can.patch(/^\/(:<id>[a-f0-9]{16})\/?$/i,
  function(req, res, params) {
    res.end(params.id + '\n')
  }
)

// Server
http.createServer(function(req, res) {
  if (!can.route(req, res)) {
    res.statusCode = 404
    res.end()
  }
}).listen(8080)

Browser

can-route also works in the browser with basically the same API:

var can = require('can-route')()

can.get(/^\/$/, function() {
  // No arguments for routes without parameters.
})

can.get(/^\/(:<name>[a-z]+)\/?$/i, function(params) {
  // The only possible argument is the param object.
})

can.get(/#\/(:<name>[a-z]+)\/$/i, function(params) {
  // It's possible to define routes based on
  // the value of location.hash.
})

window.onpopstate = function() {
  var path = window.location || '/path/to/page'
  if (!can.route(path)) {
    // Handle 404
  }
}

window.onhashchange = function() {
  var includeQueryAndHash = true
  if (!can.route(window.location, includeQueryAndHash)) {
    // Handle 404
  }
}

License

MIT

npm loves you