From basic console.log to more complex scenarios, how to use Node to print to the command line console
- Basic output using console module
- Clear the console
- Count element
- Print stack trace
- Calculate the time spent
- Standard output and standard error
- Color the output
- Create progress bar
Basic output using console module
The node provides aconsole
ModuleIt provides many very useful methods for interacting with the command line.
It is basically the same asconsole
The object you found in the browser.
The most basic and most commonly used method isconsole.log()
, It will print out the string you passed to the console.
If you pass the object, it will render it as a string.
You can pass multiple variables toconsole.log
, E.g:
const x = 'x'
const y = 'y'
console.log(x, y)
And Node will print at the same time.
We can also format beautiful phrases by passing variables and format specifiers.
E.g:
console.log('My %s has %d years', 'cat', 2)
%s
Format the variable as a string%d
or%i
Format variables as integers%f
Format variables as floating point numbers%O
Used to print object representation
example:
console.log('%O', Number)
Clear the console
console.clear()
Clear the console (behavior may depend on the console used)
Count element
console.count()
It is a convenient way.
Take the following code:
const x = 1
const y = 2
const z = 3
console.count(
'The value of x is ' + x + ' and has been checked .. how many times?'
)
console.count(
'The value of x is ' + x + ' and has been checked .. how many times?'
)
console.count(
'The value of y is ' + y + ' and has been checked .. how many times?'
)
What happens is that the count will count the number of times the string is printed, and print the count next to it:
You can count only apples and oranges:
const oranges = ['orange', 'orange']
const apples = ['just one apple']
oranges.forEach(fruit => {
console.count(fruit)
})
apples.forEach(fruit => {
console.count(fruit)
})
Print stack trace
In some cases, it is useful to print the call stack trace of the function, perhaps to answer the questionHow did you get to that part of the code?
you can use itconsole.trace()
:
const function2 = () => console.trace()
const function1 = () => function2()
function1()
This will print the stack trace. If I try this in the Node REPL, the following will be displayed:
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)
Calculate the time spent
You can easily calculate the time required for a function to run using the following methods:time()
withtimeEnd()
const doSomething = () => console.log('test')
const measureDoingSomething = () => {
console.time('doSomething()')
//do something, and measure the time it takes
doSomething()
console.timeEnd('doSomething()')
}
measureDoingSomething()
Standard output and standard error
As we have seen, console.log is very suitable for printing messages in the console. This is the so-called standard output, orstdout
.
console.error
Print tostderr
stream.
It will not appear in the console, but it will appear in the error log.
Color the output
You can use escape sequences to color the output of text in the console. An escape sequence is a set of characters that identifies a color.
example:
console.log('\x1b[33m%s\x1b[0m', 'hi!')
You can try it in Node REPL and it will printhi!
yellow.
However, this is the underlying method of doing this. The easiest way to color the console output is to use a library.chalkIt is such a library, in addition to coloring, it can also help other style settings, such as bold, italic or underlined text.
You install usingnpm install chalk
, Then you can use it:
const chalk = require('chalk')
console.log(chalk.yellow('hi!'))
usechalk.yellow
This is much more convenient than trying to remember the escape code, and the code is more readable.
Check the project link I posted above for more usage examples.
Create progress bar
progressIs a great software package, you can create a progress bar in the console. Install usingnpm install progress
This code snippet creates a 10-step bar, which completes a step every 100 milliseconds. When the bar ends, we clear the interval:
const ProgressBar = require('progress')
const bar = new ProgressBar(’:bar’, { total: 10 })
const timer = setInterval(() => {
bar.tick()
if (bar.complete) {
clearInterval(timer)
}
}, 100)
Download mine for freeNode.js manual
More node tutorials:
- Introduction to npm package manager
- Introduction to Node.js
- HTTP request using Axios
- Where to host Node.js applications
- Use Node.js to interact with Google Analytics API
- npx node package runner
- package.json guide
- Where does npm install packages?
- How to update Node.js
- How to use or execute packages installed with npm
- package-lock.json file
- Semantic version control using npm
- Should you submit the node_modules folder to Git?
- Update all Node dependencies to the latest version
- Use Node.js to parse JSON
- Find the installed version of the npm package
- Node.js flow
- Install an older version of the npm package
- Get the current folder in Node
- How to record objects in Node
- Use export to expose functions from Node files
- Difference between node and browser
- Use Node to make HTTP POST requests
- Use Node to get HTTP request body data
- Node buffer
- A brief history of Node.js
- How to install Node.js
- How much JavaScript do you need to know to use Node?
- How to use Node.js REPL
- Node, accepts parameters from the command line
- Use Node to output to the command line
- Accept input from the command line in Node
- Use `npm uninstall` to uninstall the npm package.
- npm global or local package
- npm dependencies and devDependencies
- Node.js event loop
- Understanding process.nextTick()
- Understanding setImmediate()
- Node event emitter
- Set up an HTTP server
- Use Node to make HTTP requests
- Node fs module
- HTTP request in Node using Axios
- Use Node to read files
- Node file path
- Write file with Node
- Node file statistics
- Use file descriptors in Node
- Use folders in Node
- Node path module
- Node http module
- Combine WebSockets with Node.js
- Basic knowledge of using MySQL and Node
- Error handling in Node.js
- Pug Guide
- How to read environment variables from Node.js
- How to exit from Node.js program
- Node os module
- Node event module
- Node, the difference between development and production
- How to check if a file exists in Node.js
- How to create an empty file in Node.js
- How to delete files using Node.js
- How to get the last update date of a file using Node.js
- How to determine whether the date is today in JavaScript
- How to write a JSON object to a file in Node.js
- Why use Node.js in the next project?
- Run web server from any folder
- How to use MongoDB with Node.js
- Use Chrome DevTools to debug Node.js applications
- What is pnpm?
- Node.js runtime v8 options list
- How to solve the "missing write access permission" error when using npm
- How to enable ES modules in Node.js
- How to use Node.js to generate child processes
- How to get the parsed body and the original body at the same time in Express
- How to handle file upload in Node.js
- What is the peer dependency in the node module?
- How to write a CSV file using Node.js
- How to use Node.js to read CSV files
- Node core module
- Use Node.js to increase the number of multiple folders at once
- How to print canvas to data URL
- How to create and save images using Node.js and Canvas
- How to download images using Node.js
- How to batch rename files in Node.js
- How to get the names of all files in a folder in Node
- How to use promise and wait function based on Node.js callback
- How to test NPM packages locally
- How to check the current Node.js version at runtime
- How to use Sequelize to interact with PostgreSQL
- Use Node.js to serve HTML pages
- How to solve the error that util.pump in Node.js is not a function