I used npm node-persist but I wish to use it in two modules as well, 'set()' and 'get()'

var     storage=require('node-persist'),


passing as; set(foo, bar, storage);

my problem is the package does not seem to work when passed. Is there a way to pass a npm package such as node-persist? Am I suppose to 'require' the package in each module of the project?


7 Months
Discussion Span
Last Post by alc6379

Yep. You're supposed to require it in each module.

I mean, technically you could declare the functions you wanted as variables and then inject them into the module functions that would use them, but that's kind of an anti-pattern in Javascript.

...Which is kind of funny if you're used to a language like C#, where constructor/dependency injection is all the rage. However, there are pros and cons to each approach. If you require the npm module in your module, you're tightly coupled to that module. If you inject the particular function into your module, you aren't tightly coupled, and you can change what function is called at will, based on what you injected. This could make your code more testable.

Some frameworks like Angular have DI systems built in, or you can Google "npm dependency injection" if this sounds like something you need.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.