Use Node to output to the command line

From basic console.log to more complex scenarios, how to use Node to print to the command line console

Basic output using console module

The node provides aconsoleModuleIt provides many very useful methods for interacting with the command line.

It is basically the same asconsoleThe 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)
  • %sFormat the variable as a string
  • %dor%iFormat variables as integers
  • %fFormat variables as floating point numbers
  • %OUsed 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)
})

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.errorPrint tostderrstream.

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.yellowThis 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: