express list endpoints code example

Example: express get all endpoints

const routes = {}
function routerRecursion(middleware, pointer, currentName) {
  if (middleware.route) { // routes registered directly on the app
    if (!Array.isArray(pointer['routes'])) {
      pointer['routes'] = []
    }
    const routeObj = {
      path: middleware.route.path,
      method: middleware.route.stack[0].method
    }
    pointer['routes'].push(routeObj)
  } else if (middleware.name === 'router') { // inside router
    const current = middleware.regexp.toString().replace(/\/\^\\\//, '').replace(/\\\/\?\(\?\=\\\/\|\$\)\/\i/, '')
    pointer[current] = {}
    middleware.handle.stack.forEach(function (handler) {
      routerRecursion(handler, pointer[current], current)
    });
  }
}
app._router.stack.forEach(function (middleware) {
  routerRecursion(middleware, routes, 'main')
});
console.log(routes);