Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload one file on Express without restarting?

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.

like image 957
studentTrader24 Avatar asked Oct 19 '22 05:10

studentTrader24


1 Answers

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.

like image 187
Danziger Avatar answered Oct 22 '22 02:10

Danziger