http-router

router module for node.js

http-router

router module for node.js

$ npm install http-router
var http = require('http'),
    router = require('http-router'),
    routes = router.createRouter();  // or routes = new router; 
 
routes
  .get('/', function(reqresnext) {
    res.write('Hello, ');
    return next();
  })
  .get({
    path: '/',
    callbackfunction(reqresnext) {
      res.end('World!\n');
    }
  })
  .post('/', function(reqresnext) {
    res.write('PO');
    return next();
  })
  .post('/', function(reqresnext) {
    res.end('ST!\n');
  })
  .get('/:key1/:key2', function(reqresnext) {
    res.write('key1: ' + req.params.key1 + '\n');
    res.write('key2: ' + req.params.key2 + '\n');
    res.end();
  })
  .get(function(reqresnext) {
    res.writeHead(404);
    return next();
  })
  .get(function(reqresnext) {
    res.end(http.STATUS_CODES[404] + '\n');
  });
 
http.createServer(function(reqres) {
  if (!routes.route(req, res)) {
    res.writeHead(501);
    res.end(http.STATUS_CODES[501] + '\n');
  }
}).listen(3000);
$ curl -X GET http://localhost:3000
Hello, World!
$ curl -X POST http://localhost:3000
POST!
$ curl -X GET http://localhost:3000/111/222
key1: 111
key2: 222
$ curl -X GET http://localhost:3000/unknown
Not Found
$ curl -X PATCH http://localhost:3000
Not Implemented
$ npm install
$ npm test
  • return Router - new Router instance.

Return new Router instance. It's similar to new require('http-router').

  • req http.IncomingMessage - IncomingMessage object

  • res http.ServerResponse - ServerResponse object

  • return boolean - return false if not called any callback functions.

Call appended callback functions if match to route's path. Call empty path's callback if not match to any route's path.

  • path string|function|object - request path

  • callback function(req, res, next)|undefined - callback function

    • req http.IncomingMessage - IncomingMessage object
    • res http.ServerResponse - ServerResponse object
    • next function() - call next callback function
  • return Router - return own instance.

Append path and callback function.

The MIT License. Please see LICENSE file.