Last active
October 27, 2023 23:59
-
-
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
This file contains 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
// 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