martes, 18 de marzo de 2014

NodeJS and ExpressJS - Load Controllers Dinamically



When you create an Express application you have some options for your routes file:

  1. Put all your routes in a single file (Bad idea!)
  2. Use as many requires as routes files (Not as bad as 1, but still no good)
  3. Use an existing module like express-load for example (https://github.com/jarradseers/express-load)
  4. You think 3 is too much overhead and you want to use your own code to 'require' the routes files

In this post, I'll focus in option #4.

If you prefer you can open this gist (https://gist.github.com/davibq/9633951).

This gist contains 3 files:
  • The app.js file generated when you create an express project.
  • An example of a route file with 2 GET endpoints
  • Our custom routes initializer.
If you're a little lazy and don't want to open the gist, here is the routes-initializer file:


/* Requires */
var fs = require('fs');
 
/* Constants */
/**
 * Folder where the routes are placed
 * @type {String}
 */
var ROUTES_FOLDER = './routes';
 
/**
 * This is used to identify the Routes in the folder. 
 * If the file name doesn't contain this variable value, it's not loaded.
 * This way we avoid to load Readme.md as a controller, for example
 * @type {String}
 */
var INIT_ROUTES_IDENTIFIER = 'Route.js';
 
/* Main function */
module.exports = function(app) {
 console.log('Loading Routes...');
 
 var filesInRoutesDirectory = fs.readdirSync(ROUTES_FOLDER);
 
 filesInRoutesDirectory.forEach(function(pRouteFile) {
  if (pRouteFile.indexOf(INIT_ROUTES_IDENTIFIER)>=0) {
   require(ROUTES_FOLDER+'/'+pRouteFile)(app);
  }
 });
 
 console.log('Routes Loaded...');
};


In order to get this code working, you should change the ROUTES_FOLDER variable and the INIT_ROUTES_IDENTIFIER.
This piece of code is really simple, it loads the files in the directory 'ROUTES_FOLDER' and then makes a require of each file to initialize each file.


In case you have any feedback, please leave a comment.


No hay comentarios:

Publicar un comentario