I want to create automatic routing in express, currently i can read directory and add route manually from all available files, added route can also be updated if there are changes in route file
delete require.cache[require.resolve(scriptpath)];
var routescript = {};
try {
routescript = require(scriptpath);
} catch (e){
console.log('Express >> Ignoring error route: ' + route + ' ~ >' + scriptpath);
}
var stack_index = app._router.stack_map[route]
var stack = app._router.stack[stack_index];
if (stack) {
app._router.stack[stack_index].handle = routescript;
console.log('Replace Route Stack \'' + route + '\'');
} else {
app.use(route, routescript);
var stack_index = app._router.stack_map[route] = (app._router.stack.length-1);
console.log('Add Route Stack \'' + route + '\'');
}
But those are only work only before app listen to port,
How to add / remove new route stack after the app listening to port?
One way i can think is close the server configure/add/remove the route the re listen, but i guess that is a bad practice
To use the router module in our main app file we first require() the route module (wiki. js). We then call use() on the Express application to add the Router to the middleware handling path, specifying a URL path of 'wiki'.
The app. listen() function is used to bind and listen the connections on the specified host and port. This method is identical to Node's http.
The app. get() function routes the HTTP GET Requests to the path which is being specified with the specified callback functions. Basically it is intended for binding the middleware to your application.
By using app. route() method, we can create chainable route handlers for a route path in Express.
I am so stupid....
Express 4 default is capable to add route even after it listening
So why i can't do it before? because on top of router layer stack, i add error handling layer stack, so any router layer i add after it, won't be reachable by request, because when the request is processed it will caught first by error handler layer.
so the correct method is as the following:
I have to manage what index is the error handler stack layer
located in app._router.stack
, in this case it is some layer at the
very end of array
Add new route, ex: using app.use("/something", function(req,
res, next){ res.send("Lol") })
Remove the error handler layer stacks, and put it at the very end of the router stack array
// in this case, error map is array
// contain index location of error handling stack layer
var error_handlers = app._router.stack.splice(error_map[0], error_map.length);
app._router.stack.push.apply(app._router.stack, error_handlers);
Now you are ready to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With