javascript - Separating instances of require in node -
say example have 2 files a.js , b.js both :
var some_package = require('some_package');
i call a.dosomething() , b.dosomething(), in both files, same instance used - therefore altering states inside "some_package" - didn't want happen.
what want create separate instance of some_package in , b. possible despite module caching of node.js?
a.dosomething()
, b.dosomething()
affect required module's state if function dosomething
accesses internal module scope variable. e.g.
// some_package.js var modulescopevariable = 0; // acts global module exports.dosomething = function() { return ++modulescopevariable; // change modulescopevariable };
one way around expose constructor function instead, put state in instance object, , make sure not access module scope vars in dosomething
.
// some_package.js exports.doer = function() { this.objectscopevariable = 0; this.dosomething = function() { return ++this.objectscopevariable; } } // test var = require("some_package.js"); var doer = new a.doer(); doer.dosomething();
one other way keep state control within module , tie state function
// a.js , b.js var somepackage = require("some_package.js"); var mycontext = { localstate: 0 }; // change dosomething accept context somepackage.dosomething(mycontext); // or use bind bind context new function var mydosomething = somepackage.dosomething.bind(mycontext);
lastly, possible invalidate require cache not idea. see node.js require() cache - possible invalidate?
Comments
Post a Comment