A.doSomething()
and B.doSomething()
will only affect the required module's state if the function doSomething
accesses an internal module scope variable. e.g.
// some_package.js
var moduleScopeVariable = 0; // acts like a global for this module
exports.doSomething = function() {
return ++moduleScopeVariable; // will change moduleScopeVariable for everyone
};
One way around this is to expose a constructor function instead, put the state in the instance object, and make sure not to access any module scope vars in doSomething
.
// some_package.js
exports.Doer = function() {
this.objectScopeVariable = 0;
this.doSomething = function() {
return ++this.objectScopeVariable;
}
}
// test
var A = require("some_package.js");
var doer = new A.Doer();
doer.doSomething();
One other way is just keep state control within the module and tie the state to the function
// A.js and B.js
var somePackage = require("some_package.js");
var myContext = {
localState: 0
};
// change doSomething to accept the context
somePackage.doSomething(myContext);
// or use bind to bind the context to a new function
var myDoSomething = somePackage.doSomething.bind(myContext);
Lastly, its possible to invalidate the require cache but its not a good idea. See node.js require() cache - possible to invalidate?