Last active
July 12, 2017 00:59
-
-
Save kylefeng28/c869f954d726194d50dd1f145f6e86c5 to your computer and use it in GitHub Desktop.
Require all other files in current directory in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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