Hi, I’m Dung Huynh Duc . Nice to meet you.

About Me

With over a decade of experience under my belt as a full-stack developer, I've had the opportunity to spearhead project teams at tech startups in Vietnam, Thailand, Japan and Singapore. Additionally, I have worked as a freelance engineer for various companies based in Asia Pacific, Europe, and North America.

Presently, I serve the role of a Senior Full Stack Software Engineer at ACX. I am consistently committed to exploring and acquiring knowledge on emerging and popular technologies.

nodejs
expressjs

#TIL 32 - List all express routes

blog_hero_#TIL 32 - List all express routes

I'm pretty surprised this has been an open issue for ExpressJs for a long time.

  1. Create a helper for ExpressJs
    /_ eslint-disable no-underscore-dangle _/
    import { Application } from 'express';

    // borrow from https://github.com/expressjs/express/issues/3308#issuecomment-618993790
    function split(thing: any): string {
    if (typeof thing === 'string') {
    return thing;
    }
    if (thing.fast_slash) {
    return '';
    }
    const match = thing
    .toString()
    .replace('\\/?', '')
    .replace('(?=\\/|$)', '$')
    .match(/^\/\^((?:\\[._+?^${}()|[\]\\/]|[^._+?^${}()|[\]\\/])*)\$\//);
      return match ? match[1].replace(/\\(.)/g, '$1') : `<complex:${thing.toString()}>`;
    }

    function getRoutesOfLayer(path: string, layer: any): string[] {
    if (layer.method) {
    return [`${layer.method.toUpperCase()} ${path}`];
    }
    if (layer.route) {
    return getRoutesOfLayer(path + split(layer.route.path), layer.route.stack[0]);
    }
    if (layer.name === 'router' && layer.handle.stack) {
    let routes: string[] = [];

        layer.handle.stack.forEach((stackItem: any) => {
          routes = routes.concat(getRoutesOfLayer(path + split(layer.regexp), stackItem));
        });

        return routes;

    }

    return [];
    }

    export function getRoutes(app: Application): string[] {
    let routes: string[] = [];

    app.\_router.stack.forEach((layer: any) => {
    routes = routes.concat(getRoutesOfLayer('', layer));
    });

    return routes;
    }

    export default { getRoutes };
  1. Then call from your main app
    import { getRoutes } from './express/helper';

    ...
    // show load routes on dev mode
    try {
    const allRoutes = getRoutes(app);
    logger.info('all routes', allRoutes);
    } catch (error) {
    logger.error(error);
    }