I am appending a new route to a route JavaScript file with fs.appendFileSync(...), but, as Node.Js needs to be restarted to reload files, the appended route cannot be accessed. I only need to reload the file that is being appeded to.
var express = require('express');
var router = express.Router();
module.exports = router;
/* New Routes are appended here.
Example:
router.get('/bobby', function(req, res, next){
});
*/
I've already searched Stack Overflow on ways to reload files without restarting the server, but all of the questions only involve the automated reloading for development, not the real thing. I've seen the suggestions for Nodemon and Node-Supervisor already, but those say it is just for development.
This may be a dumb question, but I don't know how to solve it.
Thank you for reading.
You can use require-reload
to do that. You should have a file where you import the router.js
module, to which you are appending new code, that should look like:
var reload = require('require-reload')(require),
var router = reload('router.js');
Each time you append new code you should do:
try {
router = reload('router.js');
} catch (e) {
console.error("Failed to reload router.js! Error: ", e);
}
The express-route-refresh
module may come in handy too. In fact, internally it also uses require-reload
.
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