Skip to content

Instantly share code, notes, and snippets.

@Nick390
Created October 28, 2023 00:00
Show Gist options
  • Save Nick390/99be172eb60a378fd9df1e9febd75636 to your computer and use it in GitHub Desktop.
Save Nick390/99be172eb60a378fd9df1e9febd75636 to your computer and use it in GitHub Desktop.
If you have a node app and you like to print all the get 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 txt file
const fs = require("fs");
// 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);
// Filter GET methods and write to a .txt file
const getRoutes = cleanedRoutes.filter(route => route.methods.includes("GET"));
const getRoutesText = getRoutes.map(route => route.path).join("\n");
fs.writeFileSync("get_routes.txt", getRoutesText);
console.log("All registered GET routes have been saved to get_routes.txt");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment