0

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.

3
  • 1
    you can generate unique string and put the new loaded module into an object? myObject[uniqueModuleName] = require(...) Commented Dec 10, 2015 at 1:55
  • Why do you need a variable name in the first place? isn't everything you need is in require.cache already? Commented Dec 10, 2015 at 2:15
  • @TLJ - that's what I thought but I was testing it and without declaring variables it seems like the modules don't persist, or something Commented Dec 10, 2015 at 3:40

1 Answer 1

1

You can't have variable variable names like that, but fortunately you can use an object, and give it property names which are variable, something like this:

var uuid = require('node-uuid');
var myModules = {};

var moduleName = 'module_' + uuid.v1();
myModules[moduleName] = require('./plugins/' + plugin);

This will guarantee you a unique name each time under moduleName that you can use.

Sign up to request clarification or add additional context in comments.

2 Comments

this is my current attempt but it's just not working for me - maybe there's something else I'm missing?
Be more specific. What's not working? (Error message)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.