2

So, I want to understand in what object NodeJs store variables in modules? I know that THIS in nodejs module returns module.exports, so I tried to find module variables in module object, but there wasn't any variable. Global object also doesn't have this variables.

For example:

const a = 0;

What object in Nodejs contains my 'a = 0' ? And can I get an access to this object and how?

Spawni
  • 83
  • 4
  • https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it – Marty Jan 25 '20 at 22:35
  • No, it's not an object. Like all variables, they are stored in a scope, and you cannot access that. – Bergi Jan 25 '20 at 22:44

2 Answers2

3

In Node, just like in all Javascript environments, the container that stores variable names and their contents is called the Lexical Environment. Each block has such an environment. When a variable is referenced (to assign a value or retrieve a value), the interpreter checks to see if such a variable exists in the current block's LE. If not, it looks to the LE in the next outer block, and so on, until it finds a matching variable name, and then it retrieves or sets the value as desired.

This container is completely internal to the engine, though - you can't explicitly interact with it via JS except by referencing variables. It's not a Javascript object.

Lexical Environments and Environment Record values are purely specification mechanisms and need not correspond to any specific artefact of an ECMAScript implementation. It is impossible for an ECMAScript program to directly access or manipulate such values.

It's not something particular to modules or Node. For example, with the following code run in a browser:

(() => {
  const a = 0;
})();

There's the outer environment (the top level, which is global), and there's also the inner environment, and the a variable name is contained in that inner environment.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

What object in Nodejs contains my 'a = 0' ?

Non, it's not in an object, it's in a function.

And can I get an access to this object and how?

You can't if you just declare it like the way you describe.

The only way to get the variable outside of the module is to export it first.

You must have it in the reference tree that linked to module.exports.

Everything inside a module are going to be wrapped to a function and the const will be declared in function scope so there is no way to get it out without exporting it.

simply do the following can make it accessible by other module:

module.exports = {
  a: a
};
Hao-Cher Hong
  • 230
  • 2
  • 6