Node.js Global Object

In a browser, the global object is window. In Node.js, it is global (or globalThis, which works in both environments). Variables and functions attached to the global object are available everywhere in your code without importing them.

Accessing the global object

console.log(global);     // prints the full global object
console.log(globalThis); // same thing, works in browsers too

globalThis was added in Node.js 12 and is the recommended cross-environment way to reference the global object.

Built-in globals

These are available in every Node.js file without any import:

  • process: info about the current Node process, environment variables, and command-line arguments. See the Process page .
  • console: console.log(), console.error(), console.warn(), console.table()
  • setTimeout(fn, ms) and setInterval(fn, ms): timers, same as in the browser
  • clearTimeout() and clearInterval(): cancel timers
  • __dirname: absolute path of the current file’s directory (CommonJS only)
  • __filename: absolute path of the current file (CommonJS only)
  • require(): import modules (CommonJS only)
  • module and module.exports: export values (CommonJS only)

setTimeout and setInterval

This example prints “tick” every second, then stops after 5 seconds:

setTimeout(() => {
  console.log('time out');
  clearInterval(interval);
}, 5000);

const interval = setInterval(() => {
  console.log('tick');
}, 1000);

__dirname and __filename

console.log(__dirname);   // /Users/you/project/src
console.log(__filename);  // /Users/you/project/src/app.js

These are only available in CommonJS modules. In ES modules, __dirname and __filename are not defined. Use import.meta.url with the URL constructor instead. See the Modules page for details.

  • Process : process.env, process.argv, and exit codes
  • Modules : CommonJS and ES module syntax