Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access NodeJS module scope variables as object

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 = /*...*/
like image 515
LJ Wadowski Avatar asked Apr 25 '16 10:04

LJ Wadowski


People also ask

Can variables used in NodeJS like var access globally?

You can access variables on the process object in any file in your project because it is global.

How can we expose Node modules?

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.

How can you make properties and methods available outside the module file in NodeJS?

The exports keyword is used to make properties and methods available outside the module file.


1 Answers

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]; 
 };
like image 83
Oluwafemi Sule Avatar answered Sep 25 '22 00:09

Oluwafemi Sule