I'm trying to achieve an effect much like what is in https://github.com/jhnns/rewire which is a great tool for doing dependency injection in node. I have a scenario where I desire this interface, but I unfortunately cannot use the same approach of modify the module wrappers prior to compilation by module system (consider it a hypothetical limitation for now).
As a result, I'm finding myself playing with dynamic scoping and I'm curious if there is a way to accomplish something like the following, but in such a way that the module contain MyClass (module1 below) doesn't need to invoke eval and can be blissfully unaware that anything is happening.
My initial take is no, but I thought I'd open this up and see if there were any ideas. The result of running the Module2 below is "{}" in the console when go2 is invoked indicating that we successfully injected {} over fs.
Can I do this without MyClass's injectSetter? Hackery is encouraged as long as we're not modifying the module system (ala the approach in rewire).
Module1:
//*******************Module 1 callee
var fs = require('fs');
var MyClass = function(){
this.value = 1;
};
MyClass.prototype.go2 = function(){
console.log(fs);
};
MyClass.injectSetter = function(fn){
eval("MyClass.setter=" + fn);
};
module.exports = MyClass;
Module2:
//*********************Module2 - caller, injector
var MyClass = require("./Module1.js");
function setter(name, value){
eval(name+"=value");
}
MyClass.injectSetter(String(setter));
MyClass.setter('fs', {});
var myclass = new MyClass();
myclass.go2();