Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the root object in Node.js

You may know the global object in Node.js:

{Object} The global namespace object.

In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

Now I stumbled over the root object which seems to be documented nowhere.

Though it seems that I can use root the same way as global:

test1.js

foo = 'bar'; // foo is defined in the global scope (no var in front of foo)

test2.js

require('./test1.js');
console.log(root.foo);

In the shell:

$ node test2.js
bar

When I inspect global and root in the shell they look the same. Try:

$ node
> global
...
> root
...

So it seems that root is the same as global. But why the redundancy? Why is root not documented? Is it deprecated?

like image 561
borisdiakur Avatar asked Feb 05 '14 13:02

borisdiakur


People also ask

What is root object node?

The root node is a node that allows to be executed using a frame instance created by the framework. Please note that the RootNode should not be executed directly but using CallTarget. call(Object...) . The structure of the frame is provided by the frame descriptor passed in the constructor.

Which is the root object in JS?

prototype is the root of almost all objects.

What is object in node JS?

Node. js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself as explained below.

How do I find the root path in node JS?

At runtime node creates a registry of the full paths of all loaded files. The modules are loaded first, and thus at the top of this registry. By selecting the first element of the registry and returning the path before the 'node_modules' directory we are able to determine the root of the application. Enjoy!


1 Answers

It is exactly the same as global.

There are a few undocumented properties like this. They date from early days of node but were left in to maintain backwards-compatibility and there is no pressing need to remove them.

You shouldn't use them in any new code, as they could be removed at any future time.

like image 96
OrangeDog Avatar answered Oct 06 '22 00:10

OrangeDog