Skip to content

Instantly share code, notes, and snippets.

@WindowsCmd
Last active December 21, 2020 21:43
Show Gist options
  • Save WindowsCmd/60f0d7ee3398bf0a97e2ce9792e9d535 to your computer and use it in GitHub Desktop.
Save WindowsCmd/60f0d7ee3398bf0a97e2ce9792e9d535 to your computer and use it in GitHub Desktop.
A Nodejs express dynamic route lodaer with support for sub dirs
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