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:27【Spider @ prisoner boy】
List of articles
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 tostderr
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
The sidebar is recommended
- Construction and development of automatic test platform based on HTTP runner
- Application of RT thread - use RT thread on stm32l051 (v. conclusion of wireless temperature and humidity sensor)
- Expose Dubbo to HTTP service
- Put the front end into the spring cloud project
- Front end learning day 4 - CSS
- Vue URL jump page with parameters
- JavaScript Chapter 13 traversal of arrays and implicit parameters of function methods
- These CSS efficiency improvement skills, you need to know!
- Beijing has opened the pilot of unmanned operation of passenger cars, and the driverless air outlet has arrived
- Test theory series - Test Case elements and design methods Part II
guess what you like
How to make the peak value of measured output voltage not less than 2V
Hexo quickly set up its own blog
Gee synthetic cloudless landsat-8 and sentry-2 data
Prototype object creation method case JavaScript specific implementation steps
YAF CLI and HTTP access modes
Simple HTML + CSS animation web page production DW simple animation web page production
The correct way for web programmers to make a pink girl series happy birthday blessing web page (HTML + CSS + JS)
HTML + CSS + JS to make simple animation web pages
HTML gourmet web page production DW static web page production div + CSS gourmet web page implementation and production
Programmer 520 Tanabata Valentine's Day confession code HTML + JS + CSS petal photo album web page template programmer confession necessary
Random recommended
- Element notify notification prompt text wrap
- Belkin: it's too early to talk about real wireless space charging
- JavaScript ES6 set (set) type* ω *
- Understand JavaScript function execution process and scope chain
- Java project: nursing home management system (java + springboot + thymeleaf + HTML + JS + MySQL)
- Java project: drug management system (java + springboot + HTML + layui + bootstrap + seals + MySQL)
- An error is reported when installing hexo during hexo deployment. What is the reason and how to solve it (tag git | keyword path)
- [front end basics] Linux command: Project Automation deployment
- Less than 100 or win Porsche, Maserati "special supply" 3.0T technical analysis
- Introduction to basic methods of math built-in objects in JavaScript
- CSS matches the nth element of the parent element
- What is the commercialization process of unmanned robotaxi after China allows driverless steering wheel?
- A lot of trouble, cook also worried: a quarter less than $8 billion
- Ajax realizes no refresh paging (no refresh paging shopping cart source code)
- [flutter topic] 101 what is flutter elements Yyds dry goods inventory
- What is the commercialization process of unmanned robotaxi after China allows driverless steering wheel?
- A lot of trouble, cook also worried: a quarter less than $8 billion
- Element acquisition of data structure c language sequence stack
- Set video label based on Vue
- CSS realizes div width adaptation, and the proportion of height and width is fixed
- How to create JavaScript custom events
- Is there any recommendation for wireless signal and wired signal power amplification circuit?
- Introduction to basic methods of math built-in objects in JavaScript
- 1000km pure electric endurance is meaningless? Then why does the car factory still try its best to extend the endurance?
- [let's implement a simple vite!] Chapter 4 - compiling single file components
- 3-11xss htmlspecialchars bypass demo
- How to conduct architecture design 𞓜 deeply reveal Alibaba cloud serverless kubernetes (2)
- Heapdump performance community special series 7: front door opener of large factory -- Application Practice of fluent
- 1、 HTML base tag
- Don't leave the crane unless necessary! A case of novel coronavirus nucleic acid positive was found in Heshan, Guangdong
- [Architect (Part 20)] self defined template of scaffold and summary of phase I
- How does JavaScript understand this algorithm
- [live review] openharmony knowledge empowerment lesson 2, phase 5 - becoming a community talent
- Understand the basic history and knowledge of HTTP
- Influence of lazy loading of Web front-end training on Web Performance
- Guangxi 2021 Guangxi landscape - blessing Lake Changshou Island
- Responsive gulp Chinese network of web front end
- Twaver-html5 basic learning (26) background
- CSS learning notes [3] floating, not separated from document flow, inheritance and stacking
- Webengine loading local html is invalid, and html is the dynamic address generated by JS, which can be solved