Last active
December 21, 2020 21:43
-
-
Save WindowsCmd/60f0d7ee3398bf0a97e2ce9792e9d535 to your computer and use it in GitHub Desktop.
A Nodejs express dynamic route lodaer with support for sub dirs
This file contains hidden or 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 path = require('path'); | |
const fs = require('fs'); | |
const routesPath = path.join(__dirname, "../routes"); | |
let Files = []; | |
function loadAllRoutes(app) { | |
ThroughDirectory(routesPath); | |
Files.forEach(name => { | |
try{ | |
const route = require(name.dir); | |
const routePath = name.routePath === "/index.js" ? "/" : `${name.routePath.slice(0, -3).replace(/\\/g, "/").replace('index', "")}`; | |
app.use(routePath, route); | |
console.log(`Loading ${routePath}`); | |
} catch (error) { | |
console.log(`Error occured with the route "${name.routePath}":\n\n${error} Ignoreing continuing`); | |
} | |
}); | |
return this; | |
} | |
function ThroughDirectory(Directory) { | |
fs.readdirSync(Directory).forEach(File => { | |
const Absolute = path.join(Directory, File); | |
if (fs.statSync(Absolute).isDirectory()) return ThroughDirectory(Absolute); | |
else return Files.push({ dir: Absolute, name: File, routePath: Absolute.split("\\routes")[1]}); | |
}); | |
} | |
module.exports = loadAllRoutes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment