Skip to content

Instantly share code, notes, and snippets.

@PierrePDP
Created October 9, 2020 15:22
Show Gist options
  • Save PierrePDP/5eb6ddf1880137d43f7e9f8fbfc99c4c to your computer and use it in GitHub Desktop.
Save PierrePDP/5eb6ddf1880137d43f7e9f8fbfc99c4c to your computer and use it in GitHub Desktop.
Dynamic route generation Express.js
registerRoutes(dir) {
//Check if recursive directory has been provided
if (!dir)
dir = '';
//Set the base directory
let baseDirectory = process.cwd() + '/routes';
//Set current directory
let currentDirectory = baseDirectory + dir;
//Get all items from directory passed with or base
let items = fs.readdirSync(currentDirectory);
//Traverse through all files and directories
for (let path of items) {
//Get the item path
let itemPath = currentDirectory + '/' + path;
//Get the stats to see if item at path is a folder or file
let itemStats = fs.lstatSync(itemPath);
//If item is a file, register the route
if (itemStats.isFile()) {
//Get the endpoint
let endpoint = require(itemPath);
//Check that endpoint exists
if (!Object.keys(endpoint).length) {
//Indicate file is malformed
console.log(`Endpoint: ${itemPath} is malformed or contains no router`);
continue;
}
//Build up the route based on folder structure
let endpointUri = '/api' + dir + '/' + path.replace('.js', '');
//Indicate what route is being registered
console.log(`Registering '${endpointUri}' route`);
try {
//Add endpoint to the router
app.use(endpointUri, endpoint);
} catch (err) {
//Handle error here
}
}
//If item is a directory, recurse back into the method
if (itemStats.isDirectory()) {
this.registerRoutes(dir + '/' + path)
}
}
}
@aruns05
Copy link

aruns05 commented Apr 18, 2023

hello
Do you have complete implementation of this ? As in some method calling this registerRoutes?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment