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!');
});