Skip to content

Instantly share code, notes, and snippets.

@midknightmare666
Last active November 5, 2019 19:50
Show Gist options
  • Save midknightmare666/1751b8d7d484ea8af6f4aea7534c72ab to your computer and use it in GitHub Desktop.
Save midknightmare666/1751b8d7d484ea8af6f4aea7534c72ab to your computer and use it in GitHub Desktop.
Dynamically load express routes from subfolder
/* main express file: app.js */
const express = require('express')
const app = express()
// other middleware
require('./routes')(app)
/* routes folder: routes/index.js */
const { readdirSync } = require('fs')
module.exports = app => {
readdirSync(__dirname).forEach(file => {
if (file === 'index.js') return
const route = file.split('.')[0]
require(`./${route}`)(app)
})
}
/* routes folder: routes/user.js */
module.exports = app =>{
app.get('/api/getUser', (req, res) => {
// ....
})
app.post('/api/postUser', (req, res) => {
// ....
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment