I would like to understand best practice for accessing variables that are defined in an external module that would then be required in several other files.
Say we have the two following files, I would like to access the value of the h variable in consume.js
//central.js
module.exports = {
common: function() {
var h = "hello";
var b = "enabled"
}
};
and
//consume.js
var g = require('./central');
//get the value of variable h from central.js
Taking this a step further, if I have the following consume.js, fetch.js and get.js files that all imported central.js, and required a common set of variables from central.js, how does one go about defining these common variables inside central.js so that the dependent files can consume them?
Thanks!
var his private to thecommonfunction while it is executing. There is no way to reach inside that function from the outside (even from within the same module) to get toh. In fact, whencommon()is not executing, there is not even an instance ofh. Now, you could makecommon()returnhand then callg.common()from anywhere to get the return value of the function.require()in that module and that gives them access to what the module has exported. This is pretty basic module logic in node.js so I'd suggest you read how exporting works from node.js modules and then ask a more specific question.