I was just wondering whether there is any best/recommended way to get variables into required modules with node js? What should be avoided?
So far I know of the following ways:
by function parameters
mymodule = require('./modules/mymodule.js')(varA,varB);
... and ...
module.exports = function (varA, varB) {}
by don't know how to call it?
mymodule = require('./modules/mymodule.js').varA;
... and ...
module.exports = function (varA, varB) {
console.log(varA)
}
through a setter class
mymodule = require('./modules/mymodule');
... and ...
module.exports = function () {
var that = this;
this.varA = null;
this.setVarA = function(varA) {that.varA = varA:}
}
Thx, I really appreciate your expertice
One way to do what I think you are trying to do is to create an object in your module with a setter and a getter:
function MyObject( varA ) {
this._varA = varA;
}
MyObject.prototype.setVarA = function( varA ) {
this._varA = varA;
}
MyObject.prototype.getVarA = function() {
return this._varA;
}
module.exports = MyObject;
and to use
var MyObject = require( './myModule' );
var myObjectInstance = new MyObject( "someValue" );
console.log( myObjectInstance.getVarA() ); //logs someValue
myObjectInstance.setVarA( "anotherValue" );
console.log( myObjectInstance.getVarA() ); //logs someOtherValue
This MDN Working With Objects article has some good info related to this.
The method above might be overkill for what you are looking for though, so you could do something simpler with just an object literal:
module.exports = function( varA ) {
return {
varA : varA
};
};
and to use
var myModule = require( './myModule' )( "someValue" );
console.log( myModule.varA ); // logs someValue