Certain objects are provided by Node.js to help us perform certain operations. These are called Global Objects. You can just use them directly. They include functions, modules, strings and objects.
We would cover the following:
1. __dirname and filename
__dirname
The __dirname global object represents the name of the current directory. That is the directly that contains the executing scripts.
The code below prints out the current directory.
// display the curent directory console.log(__dirname)
__filename
The __filename global object returns the name of the code currently executing. This is the absolute path and filename. The module however contains only the path to the file.
// display the curent directory console.log(__dirname)
2. setTimeout(cb, ms)
This is a global function used to run a callback at given interval
cb – the function to execute
ms – the number of miliseconds to delay
For example, the code below executes the function sayHello after 3 seconds. So the text ‘Welcome to Node.js’ is displayed after 3 seconds. I recommend you try it and see how it works.
function sayHello() { console.log( "Hello my friend!"); } // Call the sayHello function every 3 seconds setTimeout(sayHello, 3000);
3. setInterval(cb, ms)
The setInterval() global function is similar to the setTimeout(). However, the setInterval() executes the callback repeatedly after the given delay. Again, cb is the function to execute while ms is the number of miliseconds to delay. The max time that can be set is 24.8 days.
The function below uses setInterval(). It would continue to repeatedly execute the function.
function sayHello() { console.log( "The function just executed!"); } // Call the sayHello function every 3 seconds setInterval(sayHello, 2000);
Once the above code starts executing, then you can stop it by pressing Ctrl + C in the terminal.
4. clearInterval(timer)
Now, the setInterval() function returns a timer object. This means that you can assign the setInterval() function to a variable. We can then use the clearInterval() function to clear the interval. The clearInterval function takes a timer as parameter.
The code below stops the timer once the interval exceeds 10 seconds
var time = 0 function sayHello() { time = time + 1 console.log( time + " seconds have elapsed"); if(time > 10) { clearInterval(timer) } } // Call the sayHello function every 3 seconds timer = setInterval(sayHello, 1000);
We first create an integer variable time to keep track of the number of seconds that have passed. For each execution of the function, we increment time by 1. We also check if the time have exceeded 10 seconds. If yes, then clear the timer. I recommend you try this. Also change up the times a bit to see what you will get.
Other Objects
Other global objects include the Process object as well as the Console object. I discuss these in a separate chapter.
[…] Node.js – Global Objects […]
Useful