开发者

How should I pass options to a node module?

开发者 https://www.devze.com 2023-03-13 19:02 出处:网络
If I have a node module (I wrote) and I want to pass it a value, I could do this: var someValue process.env.SomeKey || \'\';

If I have a node module (I wrote) and I want to pass it a value, I could do this:

var someValue process.env.SomeKey || '';

var someModule 开发者_开发知识库= require('./someModule');

someModule.setOption({ 'SomeKey' : someValue });

but it feels like I am reinventing the wheel.

Is there a better way to do this or is it totally subjective?


In general, you simply export a function from the module:

module.exports = function(opts){
    return {
        // module instance
    };
}

then in the requiring page:

var mod = require('module')({ someOpt: 'val' });

But in reality, do it however you want. There's no set-in-stone standard.


I generally build modules that have similar components, sometimes just one class, or even just a selections of methods.

(function () {
  var myClass = function (opts) {
    this.opts = opts;
  };
  myClass.prototype.blah = function () {
    console.log('blah');
  };
  exports.myClass = myClass;
})();

Then in your file that is using that module.

var mymodule = require('./mymodule');
var myInstance = new mymodule.myClass({opt1: 'blah'});
myInstance.blah();

Of course you don't need to just pass around an object of options :)


Yes, it is totally subjective.

Doing it the way you demonstrated is fine. You can also just export a function or a class by assigning it to module.exports.

0

精彩评论

暂无评论...
验证码 换一张
取 消