简体   繁体   中英

“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?

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, eg

nodemon server.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM