Skip to content

Instantly share code, notes, and snippets.

@kylefeng28
Last active July 12, 2017 00:59
Show Gist options
  • Save kylefeng28/c869f954d726194d50dd1f145f6e86c5 to your computer and use it in GitHub Desktop.
Save kylefeng28/c869f954d726194d50dd1f145f6e86c5 to your computer and use it in GitHub Desktop.
Require all other files in current directory in Node.js
const fs = require('fs');
const path = require('path');
const basename = path.basename(module.filename);
const controllers = {};
fs
.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.match(/\.js$/));
})
.forEach((file) => {
let name = file.replace('.js', '');
controllers[name] = require(path.join(__dirname, name));
});
module.exports = controllers;
const fs = require('fs');
const path = require('path');
const basename = path.basename(module.filename);
const models = {};
fs
.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.match(/\.js$/));
})
.forEach((file) => {
let name = file.replace('.js', '');
models[name] = require(path.join(__dirname, name));
});
module.exports = models;
const fs = require('fs');
const path = require('path');
const basename = path.basename(module.filename);
const routes = {};
fs
.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.match(/\.js$/));
})
.forEach((file) => {
let name = file.replace('.js', '');
routes[name] = require(path.join(__dirname, name));
});
module.exports = (app) => {
Object.values(routes).forEach((route) => {
app.use(route);
})
return routes;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment