user9375768
user9375768

Reputation:

"Reloading" a file in Node.JS

In Node.JS, I'm trying to "reload" a file. I have the following code:

  delete require.cache[require.resolve("./pathToFile/" + restartModule)]

with restartModule being the file name, but I'm not sure how I could add the file back using require() and define it as the variable restartModule. For example, if restartModule is myModule, how would I add myModule.js into the var called myModule? Or maybe there's an easier way to simply "reload" a file in the cache?

Upvotes: 0

Views: 2593

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30675

You could do something simple enough like this:

function reloadModule(moduleName){
    delete require.cache[require.resolve(moduleName)]
    console.log('reloadModule: Reloading ' + moduleName + "...");
    return require(moduleName)
}

var restartModule= reloadModule('./restartModule.js');

You would have to call reloadModule every time you want to reload the source though. You could simplify by wrapping like:

var getRestartModule = function() {
    return reloadModule('./restartModule.js');
} 

getRestartModule().doStuff();

Or

var reloadModules = function() {
    return {
        restartModule = reloadModule('./restartModule.js');
    };
}

var modules = reloadModules();
modules.restartModule.doStuff();

Or:

var reloadModules = function(moduleList) {
    var result = {};
    moduleList.forEach((module) => {
        result[module.name] = reloadModule(module.path);
    });
}
var modules = reloadModules([{name: 'restartModule', path: './restartModule.js'}]);

modules.restartModule.doStuff();

You could even put the module reload on a setInterval so modules would get loaded every N seconds.

Then there's always nodemon: https://nodemon.io/ this is useful in development, whenever a source file changes it will reload your server. You just use it like node, e.g.

nodemon server.js

Upvotes: 4

Related Questions