I've never really needed to dependency inject into third party modules. If
I did, I'd rather fork the third party dependency than do some sort of
dynamic solution.
However, I do use dependency injection for (unit) testing my own stuff.
There are a ton of ways to do this but my favorite way of doing this is:
var fs = require('fs');
function Foo() { };
Foo._setBackend = function(backend) {
fs = backend;
};
module.exports = Foo;
Then in the test setup:
before: function() {
Foo._setBackend(require('./smart-fs'));
},
after: function() {
Foo._setBackend(require('fs'));
}
The nice part is that the mechanism is trivial and doesn't depend on any
external modules or require() patching, without forcing me to make "fs" a
part of the interface/params to Foo(). It doesn't work on 3rd party
modules, but I haven't needed to do that thus far. Simplest thing that
works and all that..
On Friday, July 27, 2012 7:45:48 AM UTC-7, Eldar wrote:
>
> Do we need this in Node?
>
> My answer is yes we need some (simple) way to specify the app level
> dependencies at runtime. Here is my take on
> this<https://github.com/eldargab/node-runtime>.
> Please checkout and let me know how do you feel about.
>
> But the idea is very simple:
>
> // inside any index.jsvar R = require('runtime').patchNative()var use =
> R(module).use
> use('fs', 'node_modules/third/party', require('./smart-fs'))
>
> That's it. Third party module just uses our smart file system
>
--
Job Board: http://jobs.nodejs.org/
Posting guidelines:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en