The console module


The console module is similar to the JavaScript console mechanism provided by web browsers. It is useful to debug an optimize your code. Here is our selection of a few handy methods of the console module.


1 | console.log()


In Node.js, the console.log method is used to display output to the screen. It can take one or several arguments. The function display these arguments to the screen, separated by a space when there are several of them.


// Example 1

console.log(1); // 1

console.log(1, 2, 3,); // 1 2 3

Note 1: that the console.log() is a wrapper function that uses under the hood the Writable Stream process.sdtout. In Node.js, input and output are managed respectively by a Readable Stream and a Writable Stream: process.stdin (stdin stands for standard input) and process.sdtout (sdtout stands for standard output). It is possible to use directly the Writable Stream process.sdtout to display something to the screen. For example:

// Example 2

process.stdout.write('a\n');
process.stdout.write('b\n');
process.stdout.write('c\n');

We use the escape sequence '\n' to create new lines. Note that console.log does this automatically, and is quicker to write.


Note 2: The method console.info() is an alias for console.log(). As such, they are perfectly interchangeable in Node.js.


2 | console.error()


The console.error() is similar to console.log, except that it is used to display error objects and information about errors.


Note: under the hood, the console.error() writes to a different Writable Stream: process.stderr .


3 | console.time() and console.timeEnd()


The methods console.time() and console.timeEnd() calculate how much time a function takes to run. console.time() starts a timer and console.timeEnd() stops the timer.


Timers are identified by a unique label, so both methods must be passed the same argument in order to start and stop the same timer. This argument must be a String.


console.timeEnd() automatically displays to the screen the time elapsed between the start and the end of the timer in a nice format.


// Example 3

const bigCount = () => {
  console.time('bigCount');
  for (let i = 0; i <= 30_000; i += 1) {
    console.log(i);
  }
  console.timeEnd('bigCount');
};

bigCount();

Author:
Initial publication date:
Last updated: