Hope you had a good hands-on week with the last session. Today we are going to have a sneak peek on the global objects, which is very common and necessary for any application. When you consider the normal JavaScript, we have our window object and whatever properties it has, we can access them globally. Some examples include alert, setTimeout, etc.
But since Node JS is a command line backend application and it doesn’t need a browser to run, the global object is no longer the window object. The global object in Node JS is an object called global. Much like the window object, it gives access to some methods, we can use straight out of the box in Node JS. Have a quick look at Global Objects in Node JS Documentation. It has used all the methods and properties that we can use on it.
We can see a few common methods such as console, setTimeout, setInterval, etc., which are also available in the window object in the browser as well as the global object in the Node JS.
Logging and Timers
Logging to Console
Let’s create a file named app.js in your favourite directory. I am going to show you an example of a method that’s very famous and available on this global object, both in the browser and Node JS, which is the console, and the method is console.log(). We can log things to the terminal using console.log() in Node JS. You can put anything inside the console.log() and it prints out in your command line. Let’s try out an example.
console.log(“Hello, Praveen!”);
Now save the file and get back to the terminal. Make sure you are in the same folder as the app.js. To confirm it, please try entering either dir or ls command to find the file listed at the output.
praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ ls
app.js
I am using MINGW64 here, that comes with my Portable Git installation, if you are interested. We can check the contents of a file using the cat (catalogue) command in Linux.
praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ cat app.js
console.log(“Hello, Praveen!”);
Once it’s saved, get excited to run the application by issuing the following command:
praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ node app
Hello, Praveen!
And woohoo! Node JS is going to log that in the console and then exits. This is really helpful in terms of debugging our application and trying to find what’s the value of a particular variable at a particular instance.
Let’s try other functions as well. This time, let’s try setTimeout() in our application.
praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ cat app.js
setTimeout(function () {
console.log(“Hey, it’s been two whole seconds!”);
}, 2000);
When you see the above code, the setTimeout() function takes up two arguments. The first argument is a call-back function, which is a function that needs to be called after the number of milliseconds lapsed, as given by the second argument. I have added the same console.log() function inside the call-back function and what happens is, the app takes whole two seconds to display the message.
To give the feel of the app running in front of us and not getting hung up, we can provide another console.log()function at the start of the application. Something like the following:
praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ cat app.js
console.log(“App Started.”);
setTimeout(function () {
console.log(“Hey, it’s been two whole seconds!”);
}, 2000);
This gives you an idea that the app is running and executes the code that you have written and not stuck somewhere. The same app when executed now, gives this output:
praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ node app
App Started.
Hey, it’s been two whole seconds!
In the output, the first message came off as soon as the app is executed and the next message came after two whole seconds. One of the best use cases of this setTimeout() function is that we can try to throttle the network, slow down the AJAX response and appropriately handle the user interface when the network is slow. There are the variety of other use cases as well.
Using Timers – Intervals
Since we also have setInterval() function available to us on the global object, again, much similar to window-object, let’s play something with this. We can create classy command line timer functions using it. Let’s create a timer function now. The process is really simple. I am going to create a variable called time, and initialise it to 0. setInterval() function unlike setTimeout() function, keeps executing the call back function every time the interval has lapsed.
Every second, I am going to increment the time variable by one and log it to the console. Let’s dive into the code now and see how I have written it.
praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ cat app.js
console.log(“App Started.”);
var time = 0;
setInterval(function () {
time ++;
console.log(“Hey, it’s been ” + time + ” whole seconds!”);
}, 1000);
When you try to run this app using our node app command, you will notice these:
Every second, it updates telling us the number of seconds that have been elapsed.
It doesn’t stop logging to the console.
praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ node app
App Started.
Hey, it’s been 1 whole seconds!
Hey, it’s been 2 whole seconds!
Hey, it’s been 3 whole seconds!
Hey, it’s been 4 whole seconds!
Hey, it’s been 5 whole seconds!
Hey, it’s been 6 whole seconds!
Hey, it’s been 7 whole seconds!
Hey, it’s been 8 whole seconds!
Hey, it’s been 9 whole seconds!
Hey, it’s been 10 whole seconds!
Hey, it’s been 11 whole seconds!
Hey, it’s been 12 whole seconds!
Even though the first point is suave, the second point is not really cool. This is what you call as an infinite loop. This loop is never going to end unless we tell it to end. So, if you want to end any process that runs in a terminal, all you have to do is to hit Ctrl + C on the terminal, where the process runs and that stops it.
Let’s see how to clear these timers and some other awesome global functions in our next week’s article.
Thanks to Praveen Kumar for being our guest writer this week.
We are a leading niche digital & tech recruitment specialist for the North East of England. We Specialise in the acquisition of high-performing technology talent across a variety of IT sectors including Digital & Technology Software Development.
Our ultimate goal is to make a positive impact on every client and candidate we serve - from the initial call and introduction, right up to the final delivery, we want our clients and candidates to feel they have had a beneficial and productive experience.
If you’re looking to start your journey in sourcing talent or find your dream job, you’ll need a passionate, motivated team of experts to guide you. Check out our Jobs page for open vacancies. If interested, contact us or call 0191 620 0123 for a quick chat with our team.
Follow us on our blog, Facebook, LinkedIn, Twitter or Instagram to follow industry news, events, success stories and new blogs releases.
Back to Blog