Skip to content

Instantly share code, notes, and snippets.

@AndresSepar
Forked from DarrylD/app.js
Created May 5, 2018 17:59
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 AndresSepar/be44a1e2fafd8155e73a489388ae92bd to your computer and use it in GitHub Desktop.
Save AndresSepar/be44a1e2fafd8155e73a489388ae92bd 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