Node Global Objects

Node Global Objects

Node is an open-source, cross platform, Javascript runtime environment. Global objects are built in objects that are part of Javascript and can be used directly in the application without importing any particular module. Global objects are available in all module. Some of the Node global objects are:

  1. console: It is a global object used to print to stdout.

     console.log("This is a node global objects");
    
  2. setTimeout: is used to run a call back function after at least delay in millisecond.

     setTimeout(function(){
         time = 3;
         console.log(time + " seconds has passed");
     }, 3000);
    

    setTimeout allow us to run the function after 3 seconds. The time is specified with 3000 milliSeconds.

    1000 Milliseconds = 1 seconds.

  3. SetInterval: It is used to run a call back function repeatedly at a given interval.

     var time = 0;
     setInterval(function(){
         time += 2;
         console.log(time + " seconds has passed");
     }, 2000);
    

    setInterval above allow us to run the function after every 2 seconds. To break out of the function, press "control c" on the terminal.

  4. clearInterval: It clears the interval method created by set interval methods.

     var time = 0;
     var timer = setInterval(function(){
         time += 2;
         console.log(time + "seconds has passed");
         if (time >= 5){
             clearInterval(timer);
         }
     }, 2000);
    

    The code above allow us function to run after every 2 seconds and stops after time is greater than 5.

Conclusion

Node has other global objects like the process, __dirname, TextDecoder.

This article covers the basics of Node global objects. For more in-depth learning, refer to nodejs.org/api/globals.html

Thanks for reading!!