Open CheatSheet Back To List Next Tutorial

Console, Timers and Process modules (Video Tutorial)

Console, Timers and Process modules

Intro

[0:00 Video timestamp]

This is the third in a series of tutorials on Node.js.

We created a project folder called nodejs-tutorial.
The code for the whole series is available on GitHub at github.com/LearnByCheating/nodejs-tutorial

If you are following along, open the project in your text editor and create a new folder named 3-console-timers-process.
Then open your Terminal application and go into the new folder.

This tutorial covers the console, timer and process modules.
These are built-in Node modules. They are part of the Node global object so they do not have to be imported before using them.
The Console and Timer modules are very similar to their Web API counterparts in the browser. 

Read it, watch it, do it, review it:
  • There are both a written and accompanying video version of this tutorial. There are timestamps under the headings that align with the video version of the topic.
    • Read it: For each topic heading, first read the topic. 
    • Watch it: Then watch the associated section of the video.
    • Do it: Then follow the instructions to replicate the steps on your computer.
  • The Node.js CheatSheet has a major category that aligns with this tutorial.
    • Review it: When you are done with the whole tutorial, open the CheatSheet and review the Console | Timer | Process categories from this tutorial. Make sure you understand everything, and can refer back to the CheatSheet when you are working on your own projects in the future. 

Console Module

Console in the Browser

[0:14 Video timestamp]

In the Chrome web browser, if you have Chrome Developer tools installed, you can open the console from any web page by pressing Cmd+Option+J on a Mac or Ctrl+Shift+J on Windows.
Then you can run JavaScript in the browser console, including accessing the console Web APIs.

Let's test out the Browser's Console Web API. Enter the below statement:
console.log("Testing out console log in the browser");

This will log the argument to the Browser console.

Console.log() is useful in development, especially for debugging. 

Console module in Node

[0:45 Video timestamp]

The Node Console module works in a similar way, but it logs text to the terminal instead of the browser. This is also useful for debugging, and for just logging events. 

To test it out, open the Node REPL
node

Now you can use console.log from the command line:
console.log("Testing out console log in Node");

That will log the text provided in the argument. 

Note, the logged text is not the return value of the function, it is the side effect of it. The function does not return a value, so the return value is "undefined".
.


Timer Modules

[1:06 Video timestamp]

Now we'll look at the node Timer module which also works like its browser counterpart. It is a global module so you don't need to import it before using it. 

This time we will execute JavaScript files.
Create three files: log-timeout.js, log-interval.js, and log-clear-interval.js



SetTimeout

[1:33 Video timestamp]

Populate the log-timeout file with the below:
nodejs-tutorial/3-console-timers-process/log-timeout.js
console.log(1, 'Just before setTimeout');
setTimeout(() => {
  console.log(2, "Logs after 2 seconds\nNote: setTimeout is asynchronous. So it is non-blocking. The next statement doesn't wait for it.");
}, 2000);
console.log(3, 'Just after setTimeout');

The setTimeout method takes two arguments:
  • First is the callback function that executes after the timer expires. Our callback just logs a message.
  • The second is the timer, expressed in milliseconds. So 1000 is one second.  

Then in the Terminal execute the file:
node log-timeout

The timer functions are asynchronous. That means the next JavaScript statement executes immediately, without waiting for the timer to expire.

You will see in the Terminal that three lines are logged in the following order:
1, 3, 2.

  • First is the console log before the timer.
  • Then the setTimer function is initiated.
  • Since Timers are asynchronous, it doesn't wait for the result before moving to the next line and printing log 3.
  • Two seconds later the Timer expires. Then the callback function is executed and logs line 2. 



SetInterval

[2:14 Video timestamp]

Populate the log-interval file with the below:
nodejs-tutorial/3-console-timers-process/log-interval.js
let n = 0;
setInterval(() => {
  n += 1;
  console.log(n); 
}, 1000);
// Ctrl+C to exit node from the terminal

The log-interal file executes a setInterval Timer function.
This also takes two arguments:
  • The callback function.
  • And the interval timer expressed in milliseconds. 

We start by setting variable n to 0.
In our setInterval function we increment n by 1 and log the result to the console at each interval.
Intervals are one second each.

Go to the terminal and execute the file:
node log-interval

It will log a sequential number every second.
To stop the program enter Control+C.



ClearInterval

[2:47 Video timestamp]

Populate the log-clear-interval file with the below:
nodejs-tutorial/3-console-timers-process/log-clear-interval.js
let n = 5;
const countdown = setInterval(() => {
  if (n <= 0) {
    console.log('Blastoff');
    clearInterval(countdown);
  } else {
    console.log(n); n -= 1;
  }
}, 1000);

Go to the terminal and run the file:
node log-clear-interval

  • This will print a log every second: 5 - 4 - 3 - 2 - 1 - Blastoff
  • This works like a regular setInterval, executing the callback every1000 milliseconds which is 1 second.
  • As long as n is not less than or equal to 0, then it will log n then reduce n by 1.
  • If n is less than or equal to 0 it will log "Blastoff" then execute clearInterval on the countdown variable. 
    • We assigned the setInterval to a variable named countdown. 
    • We passed that variable in to the clearInterval function. When called it stops the setInterval.



Process Module

[3:07 Video timestamp]

A process is an instance of a program running on a computer.
When you run Node.js you're running the Node process.
When you access the Process module, it can provide information about, and control over, the current Node process.
Process is a global module so it's available without having to import it first.


Get process info using properties and methods:
Let's open the Node shell and enter the below commands.
Because we are in the Node shell program, the current process is Node.
  • process Returns the process object and all its properties about the current process. 
  • process.title returns the current process title which is node.
  • process.version returns the version of Node that you're running. 
  • process.platform returns the operating system platform. Darwin is the name of the Unix flavor that Mac uses. 
  • process.cwd() calls the cwd method, which returns the path to your current working directory. 
  • process.env will return all your environment variables. 
  • process.env.PATH will return your path environment variable. 
  • process.exit() will call the exit method and close the Node process. So it will close the Node shell program.


Standard Input/Output
[4:16 Video timestamp]

  • The process object includes a standard output property called stdout to output data. 
  • Generally, it is output to the terminal, but it could be to a file or elsewhere. 
  • The console.log() method uses stdout behind the scenes to log data to the terminal. 

Create a new file called qa.js and populate it with the below:
nodejs-tutorial/3-console-timers-process/qa.js
process.stdout.write('What is your name?\n > ')
process.stdin.on('data', (data) => {
  process.stdout.write(`Hi ${data.toString().trim()}!\n`);
  process.exit();
});

Go to the terminal and run the file, then we'll talk about what it does:
node qa

  • The first statement uses the process.stdout.write method to print a question to the terminal: What is your name? 
  • The process object includes a standard input property called stdin to take input, often from the keyboard, but it could be from another source such as from a file. 
  • The process.stdin.on method listens for the data event. The listener method takes two arguments:
    1. The event, which in this case is the data event. It is triggered when the users enters their name in the Terminal.
    2. A callback function to execute when the event occurs. 

  • In the callback, we're again calling the process.stdout.write method, and printing a response to the user. We're taking the input data, the user's name, converting it to a string, and adding it to our output to say hi, followed by their name. 
  • Then we call process.exit() to exit Node.

Open CheatSheet Back To List Next Tutorial