2017-10-11 109 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

感謝它對我來說很好! :) –