How to get all js file actions using method in node js

I want to get all the actions / route of a .js file with its method type. Basically I want to create a function that returns me all the actions and methods.

router.get('/this/is/action', function (req, res, next) {
     // This action is in login.js 
}

router.post('/another/action1', function (req, res, next) {
     // This action is in signup.js 
}

So, in this type of case, my function will have to return the answer to me as if.

{
    "data":[
         {
             "url":"/this/is/action",
             "method":"get"
         }
         {
             "url":"/another/action1",
             "method":"post"
         }
    ]
}
+3
source share
1 answer

If you use express, you can use the following snippet created by dougwilson creator of the expression.

function print (path, layer) {
  if (layer.route) {
    layer.route.stack.forEach(print.bind(null, path.concat(split(layer.route.path))))
  } else if (layer.name === 'router' && layer.handle.stack) {
    layer.handle.stack.forEach(print.bind(null, path.concat(split(layer.regexp))))
  } else if (layer.method) {
    console.log('%s /%s',
      layer.method.toUpperCase(),
      path.concat(split(layer.regexp)).filter(Boolean).join('/'))
  }
}

function split (thing) {
  if (typeof thing === 'string') {
    return thing.split('/')
  } else if (thing.fast_slash) {
    return ''
  } else {
    var match = thing.toString()
      .replace('\\/?', '')
      .replace('(?=\\/|$)', '$')
      .match(/^\/\^((?:\\[.*+?^${}()|[\]\\\/]|[^.*+?^${}()|[\]\\\/])*)\$\//)
    return match
      ? match[1].replace(/\\(.)/g, '$1').split('/')
      : '<complex:' + thing.toString() + '>'
  }
}

app._router.stack.forEach(print.bind(null, []))
0
source

All Articles