Extracting routes
Express supports multiple options for application structure. Extracting elements of an Express application into separate files is one option; a good candidate for this is routes.
Let's extract our route heartbeat into ./lib/routes/heartbeat.js
; the following listing simply exports the route as a function called index
:
exports.index = function(req, res){ res.json(200, 'OK'); };
Let's make a change to our Express server and remove the anonymous function we pass to app.get
for our route and replace it with a call to the function in the following listing. We import the route heartbeat
and pass in a callback function, heartbeat.index
:
var express = require('express') , http = require('http') , config = require('../configuration') , heartbeat = require('../routes/heartbeat') , app = express(); app.set('port', config.get('express:port')); app.get('/heartbeat', heartbeat.index); http.createServer(app).listen(app.get('port')); module.exports = app;