I'm writing some code where I need to be able to load, unload, and reload modules on the fly (without closing the program). A big issue I'm running into is that there's no way to give unique names to the modules when I reload them - that is, I'm using a generalized function to reload them:
try {
delete require.cache['./plugins/'+plugin];
console.log("Reloading " + plugin + ".");
var ??? = require('./plugins/'+plugin);
}
Given that this needs to work for an unspecified number of modules (and even modules that weren't included upon startup), how can I go about naming the new Require variable (currently ??? is a placeholder).
Thanks!
edit:
for (i in fs.readdirSync("./plugins")) {
var pluginName = plugins[i].split('.')[0]
plugins[pluginName] = pluginName;
plugins[pluginName] = require("./plugins/" + pluginName);
console.log(global.plugins[i].split('.')[0]);
};
console.log(testModule1.addi(2, 3));
console.log(testModule2.mult(2,3));
This is what I have right now and it doesn't work (testModule1.addi is just addition and testModule2.mult is just mulitplication). It works just fine when I do something like:
var testModule1 = require("./plugins/testModule1");
var testModule2 = require("./plugins/testModule2");
and then call the functions.
答案 0 :(得分:1)
你不能拥有这样的变量变量名,但幸运的是你可以使用一个对象,并给它变量的属性名称,如下所示:
var uuid = require('node-uuid');
var myModules = {};
var moduleName = 'module_' + uuid.v1();
myModules[moduleName] = require('./plugins/' + plugin);
这样可以保证每次都可以使用moduleName
下的唯一名称。