Reputation: 1390
Does anyone know how to use node's native "module" module (!) to load in a module manually from file as an alternative to using the normal require mechanism?
I know it's an odd request, but I need modules that declare their variables globally (to that module) and that are wrapped as new modules each time they are required, e.g.
var private;
module.exports = {
setPrivate: function (value) {private = value}
}
To elaborate, if you call require twice in separate places with the same path you get the same module back. I need to always get a new module so that when required in twice setPrivate can only affect its own variable;
Basically, I need to work out the mechanism that require() uses to create and return a module the first time it is called. Have played around with instantiating Module directly (as in https://github.com/joyent/node/blob/master/lib/module.js#L293), but no luck - the exports property is always an empty object.
Please guys no suggestions to just use a constructor... I appreciate I have an unusual use case.
Upvotes: 1
Views: 471
Reputation: 888213
You don't need to do anything so complicated.
Instead, you can simply delete it from the cache:
delete require.cache[module.id];
Upvotes: 1