Ecco un semplice script che consente, opportunamente integrato con il proprio progetto, di stampare tutte le rotte esposte da un software con NodeJS ed Express.
Creare un file chiamato printRoutes.js. Potete metterlo dove vi pare, io l’ho messo in una cartella tools.
Tale file deve contenere questo codice sorgente:
function printRoutes(app) {
app._router.stack.forEach((middleware) => {
if (middleware.route) {
// Route middleware
const methods = Object.keys(middleware.route.methods).join(', ').toUpperCase();
console.log(`${methods} ${middleware.route.path}`);
} else if (middleware.name === 'router') {
// Router middleware
middleware.handle.stack.forEach((handler) => {
const methods = Object.keys(handler.route.methods).join(', ').toUpperCase();
console.log(`${methods} ${middleware.regexp}${handler.route.path}`);
});
}
});
}
function split(thing) {
if (typeof thing === 'string') {
return thing;
} else if (thing.fast_slash) {
return '';
} else {
const match = thing
.toString()
.replace('\\/?', '')
.replace('(?=\\/|$)', '$')
.match(/^\/\^\\(.*)\\\$\//);
return match ? match[1].replace(/\\\//g, '/') : '<complex: ' + thing.toString() + '>';
}
}
export {printRoutes}
Successivamente, dovrete richiamare tale funzionalità nell’ambito del listening della vostra applicazione.
Normalmente avrete un file denominato server.js o index.js nella root del progetto e richiamare la funzione, prima di tutto importando il modulo per effettuare la stampa delle rotte esposte dal software:
import {printRoutes} from './tools/printRoutes.js'
Quindi, richiamare il printRoutes, nel punto giusto (di solito nell’app.listen), ad esempio:
import {printRoutes} from './tools/printRoutes.js'
...
app.listen(process.env.SRV_PORT, process.env.SRV_IP, () => {
...
// Itera attraverso le rotte e stampa ogni rotta
printRoutes(app);
});
Salvate, rilanciate il server e guardate la console, troverete tutte le rotte che il vostro progetto espone.