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'
These are the main properties of the global object and are known as globals:
__dirname
and __filename
We can access global object without the global prefix. For example, global.process
and process
are the same.
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
__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 onconsole.log(__dirname);
console.log(__filename);
Result:
$ node global
/Users/Code/node
/Users/Code/node/global.js