Node.js Global Object

I. Node.js Global Object

The Node.js has a global object containing every Node-specific global property.

The global object can be accessed by either typing in console.log(global) or global in the terminal.

New properties can be assigned to global object:

global.name_of_property = 'value_of_property'
// To access global
> console.log(global)
> global
//Add new property to global
> global.color = 'blue'

II. Main Globals

These are the main properties of the global object and are known as globals:

  • process
  • require()
  • module and module.exports
  • console and console.log()
  • setTimeout() and setInterval()
  • __dirname and __filename

We can access global object without the global prefix. For example, global.process and process are the same.

1. setTimeout() and setInterval()

This global.js file will print out “set interval” every 1 second until the 5th second when the clearInterval(int) runs and stop it from carrying on.

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

const int = setInterval(() => {
  console.log("set interval");
}, 1000);

Result:

$ node global
set interval
set interval
set interval
set interval
time out

2. __dirname and __filename

  • __dirname will get the absolute path of the current folder this file is in
  • __filename will get the absolute path of the current folder with the file name added on
console.log(__dirname);
console.log(__filename);

Result:

$ node global
/Users/hatruong/Code/node
/Users/hatruong/Code/node/global.js