Created
May 2, 2014 16:17
-
-
Save DarrylD/3a236e6a4ca8ab5a0d0b to your computer and use it in GitHub Desktop.
express.js, simple dynamic route loading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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