Shock E. Shock E. - 2 months ago 5
Javascript Question

Automatically requiring "controllers" from a folder in nodejs and express

I'm trying to include all files in a directory called "controllers" which has files with express routes and some other things in them.

The problem is that the routes defined inside those files are not working, but if I paste all the code in the index file(file requiring the controllers) they work just fine.

Here's my code/files:

index.js

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

// Load and initialize the controllers.
require('./lib/controllersLoader');

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


lib/controllersLoader.js

const fs = require('fs');

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

files.forEach( fileName => {
require( __dirname + '/../controllers/' + fileName );
});


controllers/index.js

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

app.get('/', (req, res) => {
res.send('Hello, World!');
});

Answer

Inside your controller file, you are creating an express "subapp", attaching a route to it, and then doing nothing with it.

You should:

  1. Pass your app as parameter in the require, and attach routes to your original express app
  2. Return the subapp, or a router, and mount/use it from your main express app



Example:

index.js

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

// Load and initialize the controllers.
require('./lib/controllersLoader')(app);

lib/controllersLoader.js

const fs = require('fs');

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

module.exports = app => {
    files.forEach( fileName => {
        require( __dirname + '/../controllers/' + fileName )(app);
    });
}

controllers/index.js

const debug = require('../config').debug;

module.exports = app => {
    app.get('/', (req, res) => {
        res.send('Hello, World!');
    });
}
Comments