Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I pass options to a node module?

Tags:

node.js

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?

like image 967
matt Avatar asked Jun 16 '11 00:06

matt


People also ask

What are the arguments passed to the module wrapper function?

This wrapper function has 5 arguments: exports , require , module , __filename , and __dirname . This is what makes them appear to look global when in fact they are specific to each module. All of these arguments get their values when Node executes the wrapper function. exports is defined as a reference to module.


2 Answers

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.

like image 192
Nobody Avatar answered Oct 06 '22 04:10

Nobody


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 :)

like image 26
DanBUK Avatar answered Oct 06 '22 06:10

DanBUK