Last active
April 26, 2023 02:13
-
-
Save jscalderon65/f4a8b6040d681fe15ffa6ace037d377f to your computer and use it in GitHub Desktop.
Express routing auto loader
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 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