I can access node global variables as property of GLOBAL
object.
can I access module scope variables in similar way?
e.g.
var fns_x = function(){/*...*/};
var fns_y = function(){/*...*/};
function aFn(param){
/* moduleScope = something that allows me to access module scope variables */
if(moduleScope['fns_' + param]){
moduleScope['fns_' + param]();
}
}
/*...*/
module.exports = /*...*/
Or it's better to wrap those variables in object? e.g.
var fns = {
x: x = function(){/*...*/},
y: x = function(){/*...*/}
}
function aFn(param){
if(fns[param]){
fns[param]();
}
}
/*...*/
module.exports = /*...*/
You can access variables on the process object in any file in your project because it is global.
Module.exports API to expose Data to other files Node supports built-in module system. Node. js can import functionality which are exposed by other Node. js files.
The exports keyword is used to make properties and methods available outside the module file.
Short answer is NO.
Though in the ECMAScript specification variable declarations are available in the Environment Record setup for module, it is specified that this should not be accessible programmatically.
It is impossible for an ECMAScript program to directly access or manipulate such values [spec]
One workaround is to maintain a private variable as container for your functions and expose a lookup function.
var registry = {
x: function () {},
y: function () {},
};
module.exports = function (prop) {
return registry[prop];
};
Note that static analysis of the module code is lost this way.
You can also bind to the global environment but you run the risk of overriding important variables set in the module global scope.
var that = this;
that.x = function () {};
that.y = function () {};
module.exports = function (prop) {
return that[prop];
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With