Node JS Tutorial - Global Object

In this tutorial, we will learn about the Global Object in Node.js. Node.js global objects are global in nature and are available in all modules. We do not need to include these objects in our application; rather, we can use them directly.

These objects include modules, functions, strings, and objects themselves. Let's explore some of these global objects.

Console Global Object

The Console global object is used to print different levels of messages. There are built-in methods to be used for printing informational, warning, and error messages. Let's use the Console global object.

Inside the index.js file, write the following code:


conole.log("Hello World!");

Now, save and run this code. Switch to the command prompt and run the command:


node index.js

You can see the "Hello world!" message on the console.

__filename Global Object

The __filename global object represents the filename of the code being executed. This is the resolved absolute path of the code file. Let's see how we can use this.

Go to the index.js file and write the following code:


console.log(__filename);

It will print the absolute path of this file. Now, switch to the command prompt and re-run the code. You can see the absolute path of the index.js file.

__dirname Global Object

The __dirname global object represents the name of the directory that the currently executing script resides in. Let's see how we can use this.

In the index.js file, write the following code:


console.log(__dirname)

And now, re-run the index.js file. You will get the full path of the directory.

setTimeout Global Object

The setTimeout(cb, ms) global function is used to run a callback function after a given number of milliseconds. Let's see how we can use setTimeout.

Go to the index.js file and create a function, and call this function inside the setTimeout.


public function sayHello(){
console.log('Hello');
}
setTimeout(sayHello,1000);

Here, 1000 is a millisecond, which is equal to 1 second. Now, let's check. Just re-run the index.js file, and you can see that "hello" is printing continuously after 1 second.

setInterval Global Object

The setInterval global object is used to run a callback function repeatedly after a given time interval. Let's see how we can use setInterval.

Just type the following code:


setTimeout(sayHello,1000);

Now, let's check. Just re-run the index.js file, and you can see the result. The "hello" text is printing continuously after 1 second.

clearTimeout Global Object

The clearTimeout(t) global function is used to stop a timer. Let's see how we can use clearInterval.

Go to the index.js file and write the following code:


var time=1;
var timer = setInterval(function(){
timer++;
if(time>5){
clearInterval(timer);
}
console.log('Hello');
},1000);

So, let's check. Re-run the index.js file. It will print "Hello" 5 times. After 5 seconds, it will stop the timer.

In this way, we can use global objects in Node.js.