Globals

Learn how globals work in Node.js.

We'll cover the following

Everywhere

Global objects, or simply globals, are available in every module. This allows them to be used without importing a specific module. Modules like fs and events need to be imported; however, some objects, like buffer, did not need to be imported. The Buffer class is defined as a global in Node.js.

svg viewer

Some globals

A few common globals are listed below.

  • The console object is used to print to stdout and stderr.

  • Timers – such as setImmediate, setInterval, and setTimeout – are also globals that allow us to use setTimeout without importing anything in the synchronous and asynchronous modes.

  • The process object is also global. We can use this to get arguments from the command line using process.argv.

The global object

There is a difference in what is considered the global scope in Node.js and browsers. In a browser, the top-level scope is the global scope, whereas, in Node.js, the top-level scope is not the global scope; it is local to each module.

An easy way to think about it is as follows. A var defined in a browser will be global and accessible everywhere. A var defined in a Node.js module will be local to that module alone. That being said, using global variables is often not recommended.

In Node.js, the global object can be used to see whatever is available in the global scope. The code below will produce different results depending on where it is run. Running it locally, here on this platform, or in your browser console window might all return different things.

Press + to interact
console.log(global)

Get hands-on with 1300+ tech skills courses.