For small project all three ways are acceptable. For big I can say next:
Global variable is a problem
If you start to use this way, you need to defend config object like var config = {...}; config.freeze();
. In any cases global variables is a bad practice, for NodeJS especially, because it destructs modular system.
Passing config is the best way
That is the reason? TESTING
In tests you need to get some states of your config file. The first and third ways provides you next code style:
config.js
module.exports= {
a: 10
};
app.js
var config = require('config');
module.exports.func = function(){
if (config.a > 10) return 'A';
return 'B';
}
Mocha+Chai test
var expect = require('chai').except,
config = require('config'),
app = require('app');
describe('Func', function(){
it('return "A" if a > 10', function(){
config.a = 12; //DHOOO!!! (c) Homer Simpson
expect(app.func()).to.equal('A');
});
it('return "B" if a <= 10', function(){
config.a = 9;
expect(app.func()).to.equal('B');
});
config.a = 12; //return default state of config. DHOOO!!!
});
How you can see you need to have editable config, that is a bad practice (big project where each developer can change state of config in any place... DHOOO!!!)
And for second way it looks like this:
config.js
var config = {
a: 10
};
config.freezy();
module.exports = config;
app.js
module.exports.func = function(config){
if (config.a > 10) return 'A';
return 'B';
}
Mocha+Chai test
var expect = require('chai').except,
app = require('app');
describe('Func', function(){
it('return "A" if a > 10', function(){
expect(app.func({a:12})).to.equal('A');
});
it('return "B" if a <= 10', function(){
expect(app.func({a:9})).to.equal('B');
});
});
UPDATE
In this example func
is very syntetic, for real project you can see something like this:
module.js
var SubModule = require('submodule');
function MyModule(config, someVar) {
//Don't use full config, only options you needed.
//Pull out config options
this._a = config.a;
this._b = config.b;
this.doSomethink(someVar);
this.subModule = new SubModule(config);
}
MyModule.prototype.doSomething = function(){
if (this._a > 10) return 'A';
return 'B';
}
module.exports = MyModule;`
submodule.js
function MySubModule(config) {
this._c = config.c;
}
module.exports = MySubModule;