Day 4 Console Module in Node.js
30 Days of Node
Inside this article!
- Introduction
- Console and its types
- New Console
- Clear Console
- Count console
- Count reset console
- Console error
- Console time
- Console Warn
- Summary
- Repository
Introduction to console
The console
module provides us with debugging console similar to javascript console mechanism web browsers provide us. It exports two components :
- console class : It includes methods such as
console.log()
,console.warn()
,console.error()
which we can use to write to node.js streams. - Global console instance : This method is configured to write on
process.stderr
,process.stdout()
and it can be used without exclusively calling the modulerequire('console')
.
console.log() and all its variations
console.log()
is used to print to stdout
with a newline. We can pass multiple arguments. Let's see the different variations of console.log
in the example given below :
// console.log().js
// using ' ' to print
console.log('1: hello world!');
// using " " to print
console.log("2: This will also work!");
const str = 'nodejsera';
const val = 25;
// printing a string
console.log(str);
// printing a variable and replacing the
// value of variable in place of %d
console.log('4: Value of val is: %d', val);
// replacing a string in place of %s
console.log('5: %s', 'this will be printed after 5');
// concatinating in console
console.log("6: str = " + str);
The Output is:
1: hello world!
2: This will also work!
nodejsera
4: Value of val is: 25
5: this will be printed after 5
6: str = nodejsera
Create a new console
Creating a new console where stdout
will store the output and stderr.log
will store the errors ( if any ) .
The code snippet for the following is given below :
// console-custom-console.js
const fs = require('fs');
const { Console } = require('console');
const output = fs.createWriteStream('./stdout.log');
const errOutput = fs.createWriteStream('./stderr.log');
// Custom simple print
const print = new Console(output, errOutput);
// Now we can use it like console
const roll = 839147;
print.log('roll: %d', roll);
print.log('This will be stored in a file');
The Output in stdout.log
is:
roll: 839147
This will be stored in a file
console.clear()
This method is used to clear the console. Clearing the console can be useful while dealing with a big program in which you are logging a lot of stuff and while performing debugging , you want to see output after a certain point. For e.g. in the snippet below we are printing the value
which changes in the program so we will clear the previous values from the console and see only the final value in the end. This is a very simple example of how console.clear
method can be used.
// console.clear().js
// Available in Current Version
let value = 10;
console.log('Value: %d', value);
console.clear();
value *= value;
console.log('Value: %d', value);
The output of the program is:
Value: 100
console.count()
This module is used to maintains an internal label and output to stdout
the number of times console.count()
is called with any particular label. For e.g. in the snippet below labels are default , Unity and Bjarne whose occurrences are printed in the console. The default label is default
.
// console.count().js
// Available in current version
// This code counts the score of Unity, Bjarne and
// default score which goes to none of them
console.count('default');
console.count('Unity');
console.count('Bjarne');
console.count('Unity');
console.count('Unity');
console.count('Bjarne');
console.count();
The output of the program is:
default: 1
Unity: 1
Bjarne: 1
Unity: 2
Unity: 3
Bjarne: 2
default: 2
console.countReset()
his method is used to reset the counter for a particular label internally.By default it will decrement default
.
Note : Not available in LTS 6.11.3. Use latest version.
// Available in current version
// This code counts the score of remo , rj and
// default score which goes to none of them
console.count('default'); // default = 1
console.count('Unity'); // Unity = 1
console.count('Unity'); // Unity = 2
console.count('Bjarne'); // Bjarne = 1
console.countReset('Unity'); // Nothing printed
console.countReset('Unity'); // Unity = 1
console.count('Bjarne'); // Bjarne = 1
console.count(); // default=2
The output of the program is:
default: 1
Unity: 1
Unity: 2
Bjarne: 1
Unity: 1
Bjarne: 2
default: 2
console.error()
This method is used to print to stderr
. We can pass multiple arguments where first argument is primary and remaining arguments are substitution values. Snippet is given below.
Note : Not available in LTS 6.11.3. Use latest version.
const x = 10;
const y = 20;
const result = x / y;
if (result == 2) {
console.log('Result: %d', result);
} else {
console.error("Error: Error in Positioning Operands");
}
The output of the program is:
Error: Error in Positioning Operands
console.time() and console.timeEnd()
console.time
method is used to start a timer which can be used to compute the duration of the operation. Each timer is identified using unique label
. We use the same label while calling console.timeEnd
method which is used to stop the timer. Time is printed in milliseconds on stdout
by console.timeEnd() method.
console.time方法用于启动计时器,该计时器可用于计算操作的持续时间。每个计时器都使用唯一的标签进行标识。在调用用来停止计时器的console.timeEnd方法时,我们使用相同的标签。时间是通过console.timeEnd()方法在标准输出上以毫秒为单位打印的。
// console.time().js
console.time('division');
const x = 10;
const y = 20;
const result = x / y;
if (result == 2) {
console.log('Result: %d', result);
} else {
console.log('Result: ' + result);
}
console.timeEnd('division');
The output of the program is:
Resault: 0.5
division: 8.700ms
console.warn()
his method is similar to console.error
and is used to print to stderr
.
code snippet is given below :
// console.warn().js
const x = 10;
const y = 20;
const result = x / y;
if ((result % 2) == 0) {
console.log('Result: %d', result);
} else {
console.warn('Warning: Decimal number');
}
Summary
In this part of node.js tutorial series we learned about the following :
- Introduction to console
- Console class
- Global console instance
- console.log() and all its variations
- Create a new console
- console.clear()
- console.count()
- console.countReset()
- console.error()
- console.time() and console.timeEnd()
- console.warn()