Let’s check out that Node.js: What are the global objects?
As we have seen in the post, Node doesn’t need the browser for execution. Node has no window object since it is not dependent on the browser. Instead, Node has a global object.
A global object that is available throughout the Node application. We don’t need to include them in our module. We can call global objects directly using a global keyword or shorthand method.
For example. The console is the global object that is available throughout all modules, just like it is available with the window object.
We can call such an object using the window object by using window.console.log or directly console.log.
Similarly, we can call such global objects in Node using a global keyword like global.console.log. However, we must use a shorthand method like console.log() instead of a global prefix.
Unlike a window, a variable defined in the module is not available globally.
We can access this variable using a window object like window.msg. It is accessible throughout the window object.
var msg = "This is a test message"; console.log(window.msg); //Output: This is a test message // In Node.js console.log(object.msg); // Output: undefined
However, the Node module treats such a variable as a local variable. Hence, it is not accessible to a global object.
Suppose we try to access such a variable using global.msg. We will get an undefined result.
Like a window object, Node has several global objects and methods like console, setTimeout(), clearInterval(), __filename, and __dirname.
Node has global modules: console and process.
A console module is used to print information on stdout and stderr.
A process module is used to get information on the current object. It provides multiple events related to processing activities.
Thanks for reading the post on Node.js: What are the global objects?