Day 4 Console Module In Node.js

本文详细介绍了Node.js中的Console模块,包括console.log()的各种变体、创建新的console、console.clear()、console.count()及其重置、console.error()、console.time()和console.timeEnd()以及console.warn()的使用方法,是Node.js调试和日志记录的重要工具。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

30 Days of Node

在这里插入图片描述

Inside this article!

  1. Introduction
  2. Console and its types
  3. New Console
  4. Clear Console
  5. Count console
  6. Count reset console
  7. Console error
  8. Console time
  9. Console Warn
  10. Summary
  11. 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 :

  1. console class : It includes methods such as console.log(), console.warn(), console.error()which we can use to write to node.js streams.
  2. Global console instance : This method is configured to write on process.stderr, process.stdout()and it can be used without exclusively calling the module require('console').

console.log() and all its variations

console.log()is used to print to stdoutwith a newline. We can pass multiple arguments. Let’s see the different variations of console.login 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 stdoutwill store the output and stderr.logwill 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 valuewhich 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.clearmethod 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 stdoutthe 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.timemethod 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.timeEndmethod which is used to stop the timer. Time is printed in milliseconds on stdoutby 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.errorand 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
    1. Console class
    2. 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()

o console

  1. Console class
  2. 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()

Repository

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值