dynamic-routes

Dynamic routes for Express.JS

dynamic-routes

A dynamic router / loader for http://expressjs.com/

npm install dynamic-routes --save

DynamicRoutes(app, path_to_routes, [options])

var express = require('express'),
http = require('http'),
path = require('path'),
DynamicRoutes = require('dynamic-routes'),
app = express();
 
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('secrets secrets, we got extra'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
 
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
 
DynamicRoutes(app, __dirname + '/routes/');
// or 
 
/*
DynamicRoutes(app, {
src: __dirname + '/routes/',
ignore: [],
pattern: /\.js$/
});
*/
 
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
 
//routes/index.js 
module.exports = {
priority: 1000, //this is the `/` handler, should it should be the last route. 
path: '/',
 
//this function gets passed the express object one time for any extra setup 
initfunction(app) {
//app.head doesn't work with newer express.js  
},
 
GETfunction(reqres) {
res.end('GET ');
},
POSTfunction(reqres) {
res.json(req.body);
}
};
var user = module.exports = function(app) {
"use strict";
//other setup 
app.get(function(reqres) {
res.json({'user': [req.params.id, req.params, req.query, req.body]});
});
};
 
user.priority = 1;
user.path = '/user/:id?';
 
module.exports = {
path: '/user/:id?',
priority: 1,
initfunction (app) {
//setup db 
},
GETfunction(reqres) {
res.json({'user': [req.params.id, req.params, req.query, req.body]});
}
}
  • As of Express 4.x, it's recommended to use require('body-parser')() instead of express.bodyParser(), check this.