The Node.js runtime

Output to the command line using Node

Learn how to output to the command line in Node.js with the console module, from console.log and format specifiers to count(), trace(), time(), and colors.

Basic output using the console module

Node provides a console module with tons of useful ways to interact with the command line.

It works like the console object you know from the browser.

The most basic method is console.log(), which prints the string you pass to it.

If you pass an object, Node renders it as a string.

You can pass multiple variables:

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

Node prints both.

You can also format phrases by passing variables and a format specifier:

console.log('My %s has %d years', 'cat', 2)
  • %s format a variable as a string
  • %d or %i format a variable as an integer
  • %f format a variable as a floating point number
  • %O used to print an object representation

Example:

console.log('%O', Number)

Clear the console

console.clear() clears the console (the behavior might depend on the console used)

Counting elements

console.count() is a handy method.

Take this 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?'
)

count tracks how many times each label was printed and shows the count next to it:

The value of x is 1 and has been checked .. how many times?: 1
The value of x is 1 and has been checked .. how many times?: 2
The value of y is 2 and has been checked .. how many times?: 1

You can just count apples and oranges:

const oranges = ['orange', 'orange']
const apples = ['just one apple']
oranges.forEach(fruit => {
  console.count(fruit)
})
apples.forEach(fruit => {
  console.count(fruit)
})

Sometimes you want to see the call stack. Maybe you are asking how did you reach that part of the code?

Use console.trace():

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

This prints the stack trace. In the Node REPL you might see something like:

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 measure how long a function takes with time() and timeEnd(). The label you pass is the same one you pass to timeEnd():

const doSomething = () => console.log('test')
const measureDoingSomething = () => {
  console.time('doSomething()')
  //do something, and measure the time it takes
  doSomething()
  console.timeEnd('doSomething()')
}
measureDoingSomething()

stdout and stderr

console.log writes to standard output, or stdout.

console.error writes to stderr.

It will not appear in the console the same way, but it will show up in the error log.

Color the output

You can color console output with escape sequences. An escape sequence is a set of characters that picks a color.

Example:

console.log('\x1b[33m%s\x1b[0m', 'hi!')

Try that in the Node REPL and it prints hi! in yellow.

This is the low-level way. The simplest approach is a library. Chalk handles colors and other styling like bold, italic, and underline.

Install it with npm install chalk, then:

const chalk = require('chalk')
console.log(chalk.yellow('hi!'))

chalk.yellow is much easier than memorizing escape codes, and the code reads better.

Check the project link I posted above for more usage examples.

Create a progress bar

Progress is a nice package for a console progress bar. Install it with npm install progress.

This snippet creates a 10-step progress bar. Every 100ms one step completes. When the bar finishes 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)

Lesson completed