Skip to content

Instantly share code, notes, and snippets.

@jscalderon65
Last active April 26, 2023 02:13
Show Gist options
  • Save jscalderon65/f4a8b6040d681fe15ffa6ace037d377f to your computer and use it in GitHub Desktop.
Save jscalderon65/f4a8b6040d681fe15ffa6ace037d377f to your computer and use it in GitHub Desktop.
Express routing auto loader
const debug = require('debug')('backend:route-auto-loader')
const fs = require('fs')
const path = require('path')
const ROUTES_PATH = 'src/Routes'
function slash(text) {
return text.replace(/\\/g, '/')
}
function routeLoader(app, routerPath = ROUTES_PATH) {
fs.readdirSync(routerPath).forEach((file) => {
const filePath = slash(path.join(routerPath, file))
const stat = fs.statSync(filePath)
if (stat.isDirectory()) {
debug('Loading dir %s', filePath.replace(ROUTES_PATH, ''))
routeLoader(app, path.normalize(filePath))
} else {
let route = slash(
filePath
.replace(ROUTES_PATH, '')
.replace('.js', '')
.replace('index', ''),
)
let requireFilePath = path.resolve(filePath)
debug('Loading route %s', route)
app.use(route, require(requireFilePath))
}
})
}
module.exports = routeLoader
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment