Skip to content

Instantly share code, notes, and snippets.

@LiuJi-Jim
Created August 14, 2014 13:18
Show Gist options
  • Save LiuJi-Jim/9102b8d5c116ab096b33 to your computer and use it in GitHub Desktop.
Save LiuJi-Jim/9102b8d5c116ab096b33 to your computer and use it in GitHub Desktop.
express.js auto route,遍历controllers目录里的所有js文件,对里面每个module的每个属性都当做一个/:controller/:action,作自动路由(就跟ASP.NET MVC差不多啦!)
// app.js
for (var controller in routes){
var mod = routes[controller];
app.all('/' + controller + ':action', function(req, res){
var action = req.params.action;
if (action in mod){
mod[action](req, res);
}else{
res.statusCode = 404;
res.send('404 not found');
}
});
}
// routes.js
var controllerPath = path.join(__dirname, 'controllers');
fs.readdirSync(controllerPath).forEach(function(filename){
var extname = path.extname(filename);
if (extname !== '.js') return;
var fullname = path.join(controllerPath, filename);
var stats = fs.statSync(fullname)
if (stats.isFile()){
try{
var moduleName = path.basename(filename, extname);
exports[moduleName] = require('./controllers/' + moduleName);
}catch(ex){
console.log('route error', ex);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment