2017-10-11 20 views
6

Chcę pobrać wszystkie działania/ścieżki pliku .js z jego typem metody. Zasadniczo chcę utworzyć funkcję, która zwróci mi wszystkie działania i metody.Jak uzyskać wszystkie akcje plików js z metodą w węźle 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 
} 

W takim przypadku moja funkcja będzie musiała zwrócić mi odpowiedź wygląda jak pod.

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

Użyłem route.stack, ale dostarczy mi tylko te akcje i metody. –

Odpowiedz

0

Jeśli używasz wyrazić można użyć poniższy fragment utworzony przez dougwilson twórcy Express.

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

Dziękuję za odpowiedź. Próbuję zaimplementować to, ale mam błąd w wierszu 13. Który jest SyntaxError: nieoczekiwany token) –

+0

Mam kilka błędów składniowych tam teraz powinien działać. –

+0

Dzięki za to dobrze dla mnie !!! :) –

Powiązane problemy