Created
April 6, 2012 15:32
-
-
Save klovadis/2320816 to your computer and use it in GitHub Desktop.
How to include all routes in a folder for express using node-walker
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
// include the express framework | |
var express = require('express'); | |
// include the node-walker module | |
// -> npm install node-walker | |
var walker = require('node-walker'); | |
// the express server instance | |
var app = express.createServer(); | |
// a variable to count | |
var i = 0; | |
// route path from where we will load the routes | |
var routepath = __dirname + '/routes'; | |
console.log('Including routes in ' + routepath + '\n'); | |
// start walking the folder | |
walker(routepath, function (err, filename, next) { | |
// an error occurred somewhere along the lines | |
if (err) throw err; | |
// filename | |
if (filename !== null) { | |
var route; | |
// increment the counter | |
i++; | |
// "require" the file | |
route = require(filename); | |
// call the "register" method for the route | |
// provide app as an argument, could also | |
// provide a database connection, settings | |
// or the like | |
route.register(app); | |
} | |
// there are more files to come | |
if (next) { | |
// continue with next file | |
next(); | |
} else { | |
// no more files to come, we're done | |
console.log('\nDone. ' + i + ' route files have been included.'); | |
// now we start listening | |
app.listen(80); | |
} | |
}); |
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
// assume all routes are stored in a subfolder called "routes" | |
// this test.route.js exports a function called "register" | |
// which is then called in the main file and takes the express | |
// app as an argument | |
var exports = module.exports; | |
exports.register = function (app) { | |
// register the route | |
app.get('/test', function (req, res) { | |
res.end('Hello world.'); | |
}); | |
// log that route has been registered | |
console.log('GET /test'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment