Skip to content

Instantly share code, notes, and snippets.

@mrhammadasif
Last active June 21, 2017 10:27
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 mrhammadasif/04b016081bde6849ae4b97df2b3d8c12 to your computer and use it in GitHub Desktop.
Save mrhammadasif/04b016081bde6849ae4b97df2b3d8c12 to your computer and use it in GitHub Desktop.
Load Dynamic Routes Recursively in ExpressJS App
// A file in `routes/` folder
module.exports = (function(app, router){
router
.route('/books')
.get((req, res, next)=>{
if(err){
next(err);
// send it to error handler
}
else{
res.json({"books": ["book1", "book2", "bookn"]});
}
});
router
.route('book/:id')
.get((req, res, next) => { /* Custom Functionality for getting specific book */})
.put((req, res, next) => { /* Custom Functionality for updateing specific book record in DB */});
})(app, router);
// routes
processRoutePath(__dirname + "/routes");
function processRoutePath(route_path) {
fs.readdirSync(route_path).forEach(function(file) {
var filepath = route_path + '/' + file;
fs.stat(filepath, function(err,stat) {
if (stat.isDirectory()) {
processRoutePath(filepath);
} else {
let router = express.Router();
console.info('Loading route: ' + filepath);
require(filepath)(app, router);
app.use("/" + filepath, router);
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment