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

var     storage=require('node-persist'),
            set=require('./set.js'),
            get=require('./get.js');

storage.initSync();

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?

Thanks

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.