Skip to content

Instantly share code, notes, and snippets.

@Nick390
Last active October 27, 2023 23:59
Show Gist options
  • Save Nick390/8f57435fff470535340556144c2facec to your computer and use it in GitHub Desktop.
Save Nick390/8f57435fff470535340556144c2facec to your computer and use it in GitHub Desktop.
If you have a node app and you like to print all the routes in your app to see what user can go to you can use this code in index.js that will print all the routers to json file
// Function to recursively find all routes
function listRoutes(router, parentPath = "", routeList = []) {
if (!router || !router.stack) {
console.error("Invalid router:", router);
return routeList;
}
router.stack.forEach((layer) => {
if (layer.route) {
routeList.push({
path: parentPath + layer.route.path,
methods: Object.keys(layer.route.methods).join(", ").toUpperCase(),
});
} else if (layer.name === "router") {
const newParentPath = parentPath + layer.regexp.source.replace("^\\/", "").replace("\\/?(?=\\/|$)", "");
listRoutes(layer.handle, newParentPath, routeList);
}
});
return routeList;
}
// Clean up the routes and remove unwanted characters
const cleanRoutes = (routes) => {
return routes.map(route => ({
path: route.path.replace("?(?=\\/|$)", ""),
methods: route.methods,
}));
};
// Use the function on app._router instead of app
const allRoutes = listRoutes(app._router);
const cleanedRoutes = cleanRoutes(allRoutes);
const fs = require("fs");
// Save to a JSON file
fs.writeFileSync("cleaned_routes.json", JSON.stringify(cleanedRoutes, null, 4));
console.log("All registered routes have been saved to cleaned_routes.json");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment