Skip to content

Instantly share code, notes, and snippets.

@DarrylD
Created May 2, 2014 16:17
Show Gist options
  • Save DarrylD/3a236e6a4ca8ab5a0d0b to your computer and use it in GitHub Desktop.
Save DarrylD/3a236e6a4ca8ab5a0d0b to your computer and use it in GitHub Desktop.
express.js, simple dynamic route loading
//all of your express config stuff
var express = require('express')
, app = express()
//load api routes (app of the files from /api)
require('./api').boot(app)
//rest of your expressjs stuff
//this goes inside a api folder or something
var fs = require('fs')
, path = require('path')
, routePath = path.resolve( __dirname )
, colors = require('colors');
//this little guy will grab all the files from the /api folder
//and load up the routes inside that file
exports.boot = function(app) {
fs.readdirSync(routePath).forEach(function(file) {
//we dont need to make a route for this current file
if(file !== 'index.js'){
var cleanPath = routePath + '/' + file.substr(0, file.indexOf('.'));
//resolving route for cross-platform
var route = path.resolve(cleanPath)
console.log('--Adding routes from: '.yellow + file)
//load the route
require(route)(app);
}
});
}
//example of an route
// put this inside that api folder too
var db = require('../config/db-schema')
, _ = require('underscore');
module.exports = function(app) {
//return a list of all team members
app.get('/api/teamMembers', function(req, res){
db.TeamMembers.find({}, function (err, members) {
if (err){
console.log(err);
}
res.send(members);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment