2017-10-11 112 views
6

我想使用它的方法类型获取所有.js文件的操作/路由。 基本上我想做一个函数,返回所有的动作和方法。如何使用节点js中的方法获取所有js文件操作

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 
} 

所以,在这种情况下,我的函数将不得不返回我的响应看起来像下。

{ 
    "data":[ 
     { 
      "url":"/this/is/action", 
      "method":"get" 
     } 
     { 
      "url":"/another/action1", 
      "method":"post" 
     } 
    ] 
} 
+0

我已经使用route.stack,但它会给我只有该文件的动作和方法。 –

回答

0

如果您使用快递,您可以使用以下由dougwilson快递创建者创建的片段。

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

谢谢你的回答。我试图实现这一点,但我得到错误在第13行。这是SyntaxError:意外的令牌) –

+0

我现在有一些语法错误,它应该工作。 –

+0

感谢它对我来说很好! :) –