0

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?

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

The thing is, with that var test, I wouldn't know the name of the module, it's a variable (restartModule)
Oh yes, I'd just name it whatever.. e.g. myModule, restartModule.
yeah but it needs to be called by whatever value restartModule has. So it restartModule is equal to "name" then the var should be called "name"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.