Skip to content

Instantly share code, notes, and snippets.

@William-Yeh
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save William-Yeh/10245319 to your computer and use it in GitHub Desktop.
Save William-Yeh/10245319 to your computer and use it in GitHub Desktop.
load all Node.js (including Express) route definitions
/**
* load all Node.js (including Express) route definitions.
* in most cases you should only need to modify the app_routes[] array.
*
* inspired by the article:
* - http://stackoverflow.com/questions/5778245/expressjs-how-to-structure-an-application
*
* @author William Yeh <william.pjyeh@gmail.com>
* @date 2014-04-09
* @license MIT
*
* @url https://gist.github.com/William-Yeh/10245319
*/
"use strict";
/**
* route definitions (corresponding to ./routes/*.js files)
var app_routes = [
'index' // ./routes/index.js
, 'route1' // ./routes/route1.js
, 'route2' // ./routes/route2.js
];
*/
/**
* init route mappings
*
* @param {array} app_routes - route names
*/
exports.loadRoutes = function(app_routes) {
if (! Array.isArray(app_routes))
return;
app_routes.map( function(route_name) {
if (typeof route_name !== 'string')
return;
console.log("Loading route: " + route_name);
// load individual routes dynamically
var route = require('./routes/' + route_name);
// invoke this route's init(), if any
if (typeof route.init === "function") {
route.init();
}
});
};
/**
* init route mappings
*
* @param app - Express app object
* @param {array} app_routes - route names
*/
exports.loadExpressRoutes = function(app, app_routes) {
app.disable('x-powered-by');
if (! Array.isArray(app_routes))
return;
app_routes.map( function(route_name) {
if (typeof route_name !== 'string')
return;
console.log("Loading route: " + route_name);
// load individual routes dynamically
var route = require('./routes/' + route_name);
// invoke this route's init(), if any
if (typeof route.init === "function") {
route.init(app);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment