Going Deep with Color & Node Util

Use Node.js’ built-in Util module to add color and depth to your terminal logs.

Motherland Chronicles #23 — Dive by Photographer Zhang Jingna

Let’s create a new file called log_log.js

Next, we will require the built in Node module called ‘util’

const util = require('util')

Util has 5 methods, but for this discussion, we will be concentrating on the inspect method which inspects the specified object and returns the object as a string representation.

util.inspect(object[, options])

There are many options available with inspect, but we will only be using the first 3. Let’s create a object called options.

const options = { 
showHidden: false,
depth: null,
colors: true

The showHidden property is to false, as we do not want to show the arrays non-enumerable symbols and properties (length is such a property).

What I have found most valuable about util is the depth option which tells inspect how many levels deep to show while formatting a nested object as a string. This is very useful for inspecting large complicated objects. The default depth is set to 2, however, to show the entire depth of a nested object you may pass null as the value.

Lastly we will set the colors option to true, which will style the output with ANSI color codes. These colors are customizable as we will see later.

Let's try it out with a simple array with no nested objects:

const data = [
'name': 'Ren',
'id': 1
'name': 'Stimpy',
'id': 2
'name': 'Fire Chief',
'id': 3
const inspect = util.inspect(data, options)

Inside of terminal run the following command:

node log_log.js

You should see the following output:

Compare this to the standard console.log() method:

However, if we were to add nested properties to the objects, console.log() would only show 2 levels deep.

const data = [
'name': 'Ren',
'id': 1,
'preferences': {
'food': 'steak',
'drink': 'bourbon',
'ice_cream': 'soap bar',
'favorite_episode': 'Space Madness',
'hobbies': {
'sports': ['soccer', 'bad mitten'],
'dancing': ['salsa', 'bachata'],
'music': {
'alternative': ['Pearl Jam', 'Nirvana'],
'glam_rock': ['Mötley Crüe', 'Poison'],
'country': ['Johnny Cash', 'George Strait']

Using util with the depth option set to null we can see a complete picture of the data object regardless of the depth.

In the next article, we will add custom text and background colors to our Node logs. See you soon!