The Global Object in Node.js
In this article you will get to know about the Global Object in Node.js
These Global Objects can be seen in modules that are their in Node.js. The Global object in Node can be considered as an object called Global.If youa are familiar with my previous articles on introduction, you may have already created our first command using Node (Click here to get the article). Move on to the same file and open your command line.
Before starting move on to the Node.js Documentation to get familiar with Global objects.
Here you can see the documentation has given set of Global objects,Among them setInterval,setTimeout can be considered as window objects as well . lets try an example.Here I will write an function to setTimeout function
setTimeout(function(){
console.log('You are after 5 seconds');
},5000);
In this function you will get an timeout of 5 seconds which will be shown in the time out of 5000 milliseconds. When you run this in the terminal you will get the output of 'You are after 5 seconds' which will delay the output for 5 seconds.
Few More Examples
Set Time Intervals
var time =0; // Initial time is set to 0
var timer = setInterval(function(){
time +=2;// Always to keep a gap of 2 seconds
console.log(time+' '+'seconds have passed');
if (time>8) {
clearInterval(timer);// stops the timer when exceeds 8 seconds
}
},3000);
output:
__dirname
To show my current working directory.
console.log(__dirname); //__dirname is also called in global object
output:
__filename
To show the current working file.
console.log(__filename); //__filename is also called in global object
output:
These can be used in anywhere in our Node Application. Because they set on the global object.Hope to see you soon with Node.js Modules.
Comments
Post a Comment