current position:Home>Node. Summary of methods of outputting console to command line in JS

Node. Summary of methods of outputting console to command line in JS

2022-04-29 12:43:27Spider @ prisoner boy

Use the basic output of the console module

Node.js Provides console modular , This module provides a number of very useful methods to interact with the command line .

Most basic 、 The most common method is console.log(), This method prints the string passed into the console .

If you pass in an object , Then it will be rendered as a string .

You can pass in multiple variables to console.log, for example :

JS
const x = 'x'
const y = 'y'
console.log(x, y)

Node.js It will all print out .

You can also format terms by passing in variables and format specifiers .

for example :

JS
console.log(' my %s already %d year ', ' cat ', 2)
  • %s Will format the variable as a string
  • %d Will format the variable as a number
  • %i The variable is formatted as its integer part
  • %o Will format the variable as an object

for example :

JS
console.log('%o', Number)

Clear the console

console.clear() Will clear the console ( Its behavior may depend on the console used ).

Element count

console.count() Is a convenient way .

Use the following code :

JS
const x = 1
const y = 2
const z = 3
console.count(
  'x  The value of is  ' + x + '  And it has been checked several times ?'
)
console.count(
  'x  The value of is  ' + x + '  And it has been checked several times ?'
)
console.count(
  'y  The value of is  ' + y + '  And it has been checked several times ?'
)

count Method counts the number of times the string is printed , And print the count next to it :

JS
const arr = [' One ', ' Two ',' 3、 ... and ']
const arr1 = [' Four ']
arr.forEach(fruit => {
    
  console.count(fruit)
})
arr1.forEach(fruit => {
    
  console.count(fruit)
})

Print stack trace

In some cases , It's useful to print the call stack trace of a function , You can answer the following questions : How to get to that part of the code ?

have access to console.trace() Realization :

JS
const function2 = () => console.trace()
const function1 = () => function2()
function1()

This prints the stack trace . If in Node.js REPL Try this operation , The following will be printed :

BASH
Trace
    at function2 (repl:1:33)
    at function1 (repl:1:25)
    at repl:1:1
    at ContextifyScript.Script.runInThisContext (vm.js:44:33)
    at REPLServer.defaultEval (repl.js:239:29)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at REPLServer.onLine (repl.js:440:10)
    at emitOne (events.js:120:20)
    at REPLServer.emit (events.js:210:7)

Calculation time

have access to time() and timeEnd() Easily calculate the time required for the function to run :

JS
const doSomething = () => console.log('test')
const measureDoingSomething = () => {
    
  console.time('doSomething()')
  // And measure the running time of the function .
  doSomething()
  console.timeEnd('doSomething()')
}
measureDoingSomething()

stdout and stderr

console.log Ideal for printing messages in the console . This is called standard output ( Also known as stdout).

console.error It will print to stderr flow . It won't appear in the console , But it will appear in the error log .

Shade output

have access to Escape sequences Coloring the output of text in the console . An escape sequence is a set of characters that identify colors .

for example :

JS
console.log('\x1b[33m%s\x1b[0m', ' Hello ')

Can be in Node.js REPL Try to , It will print in yellow Hello .

Of course , This is the underlying method for performing this operation . In order to be more convenient, I recommend a plug-in library . Chalk Is such a library , In addition to coloring it , It also helps with the setting of other styles ( For example, make text bold 、 Italic or underlined ).

have access to npm install chalk Installation , And then you can use it :

JS
const chalk = require('chalk')
console.log(chalk.yellow(' Hello '))

Compared to trying to remember escape code , Use chalk.yellow Much more convenient , And the code is more readable .

Create a progress bar

Progress It's a great package , You can create a progress bar in the console . Use npm install progress Installation .

The following code snippet will create a 10 Step progress bar , Every time 100 Complete one step in milliseconds . When the progress bar ends , Then clear the timer :

JSconst ProgressBar = require('progress')
const bar = new ProgressBar(':bar', {
     total: 10 })
const timer = setInterval(() => {
     
 bar.tick()  
 if (bar.complete) {
      
   clearInterval(timer)  
 }}, 100)

Simple summary

console.log() This method prints the string passed into the console .
console.clear() Clear the console .
console.count() Check how many times a variable is used .
console.trace() This prints the stack trace .
console.time() and console.timeEnd() You can print the execution time of a function .
console.error It will print to stderr Stream in error log .
Chalk The plug-in can add color to printing more conveniently .
Progress The plug-in can create a progress bar in the console .

copyright notice
author[Spider @ prisoner boy],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291112163024.html

Random recommended