Route improvements
We now have quite a few routes required in our Express server; let's clean this up. A common pattern in node.js
is to include an index
file that returns all files in its current directory. We will use require-directory
to do this for us:
npm install require-directory –save
Let's create a new module ./lib/routes/index.js
. with the following code:
var requireDirectory = require('require-directory'); module.exports = requireDirectory(module, __dirname, ignore);
Now, all routes in the ./lib/routes/
folder will be exposed under a single variable, routes
:
var express = require('express') , http = require('http') , config = require('../configuration') , db = require('../db') , routes = require('../routes') , notFound = require('../middleware/notFound') , id = require('../middleware/id') , app = express(); app.use(express.bodyParser()); app.set('port', config.get('express:port')); app.use(express.logger({ immediate: true, format: 'dev' })); app.param('id', id.validate...