Node.JS Global Objects

In almost all of the previous articles we import some module and then used its function to perform a particular task. For instance, in the last two articles we used “File System” module named “fs” and used its readFile() and writeFile() functions to read and write files. We used “require” command in order to import and use “fs” module. However there are some modules that globally available and we do not need “require” statement to include those modules into our applications. Rather, they are directly available. Such modules are called node.js global objects. These global objects can be classes, strings, functions etc. In this article we shall discuss some of these node.js global objects.

__dirname and __filename

The _direname global objects return full path of the directory in which the current script is running. Similarly, the __filename global object returns complete file name with the resolved absolute path. Take a look at the following example.

console.log( __dirname );
console.log( __filename );

Download the code Try the code

setTimeout(callback, milliseconds) and clearTimeout(callback, milliseconds)

The setTimeout(cb, ms) method is used to execute a particular function after specified amount of time. The function takes callback as the first parameter and time in milliseconds as the second parameter. Similarly, clearTimeout(timer) function clears or stop previously set timer. Take a look at the following code to see how these functions work.

function printWelcome(){
   console.log( "Welcome to Knowledge Hills!");

function printWelcome2(){
   console.log( "Welcome to Knowledge Hills Again");

var timer = setTimeout(printWelcome, 3000);
var timer2 = setTimeout(printWelcome2, 3000);


Download the code Try the code

In the above code we declare two functions “printWelcome” and “printWelcome2”. Next we use setTimeout function twice and add both “printWelcome” and “printWelcome2” functions a callbacks. The time for the execution of these callback functions is set to three seconds. Next, we use clearTimeout function and pass it the timer for the “printWelcome2” function. This clears the timer for the second function. Now if you run the above code, you shall see that the first method i.e. “printWelcome()” shall execute after three seconds, however the second method i.e.”printWelcome2()” shall not execute since its timer has been cleared via clearTimeout function.

<<< Node.JS File System Useful FunctionsNode.JS Web Server >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .