I'm trying to write a module to dynamically load all the files from my "controllers" folder, and then add them to the main express instance as routers.

The files inside the controllers export an Express router. So the code basically does the next things:

  1. Read the "controllers" dir.
  2. Store what each router exported by the file to a var.
  3. "Merge" the router with the main app instance(that is exported by the index.js file).

I had some issue generating the controllers name, because they need to be dynamic variables, so I created an object and then I passed the name using the brackets syntax, and I think that they may be stored twice, once in that Object I created and the second it the Express instance (if that makes any sense...).

And overall I think it can be created better.

The code:


// Expressjs
const express = require('express');

// Setting and exporting app so this instance could be used in other files.
const app = module.exports = express();

// Load and initialize the controllers, and passing them the main express instance.

 * Initializing the listener according to the settings in the config.
app.listen(config.server.port, err => {
    // Throwing an exception since the whole app depends on this.
    if (err) throw err;
    console.log(`SERVER: Listening on port ${config.server.port}`);


// Get the main express app instance
const app = require('../index');
const fs = require('fs');

// Getting an Array of the files in the 'controllers' folder.
let files = fs.readdirSync( __dirname + '/../controllers');

files.forEach( fileName => {
    // Stripping the filename from the extension and storing it for later use
    // as the Controller name.
    let contName = /.+(?=\.\w?)/.exec(fileName)[0];

    // Create a new object to hold the controllers,
    // I use an Object because that helps me with dynamic variables.
    let controllers = {};

    // Store the required module in a variable.
    controllers[contName] = require( __dirname + '/../controllers/' + fileName );

    // Setting the route string.
    let route;

    // If file is the index file, the route should be '/'
    if (fileName === 'index.js') {

        route = '/';

    } else {

        // Get filename without extension using regex
        route = '/' + contName;


    app.use(route, controllers[contName]);

./controllers/example.js(in this case its the index)

const router = require('express').Router();
const debug = require('../config').debug;

    res.send('Hello, World!');

module.exports = router;

Your Answer


Browse other questions tagged or ask your own question.