Better loggin in Node

In nodeDecember 1, 20211 min read

Debugging objects in the browser’s console is very convenient. You get a super friendly UI that allows you to inspect any nested objects within the original one. Not only that, but you can also inspect up to the Object prototype.

Given the following object

const object = {
  key: 'level1',
  arr: [1, 2, 3],
  value: {
    key: 'level2',
    arr: [4, 5, 6],
    value: {
      key: 'level3',
      arr: [7, 8, 9],
      value: { key: 'level4', arr: [10, 11, 12], value: { key: 'end' } },
    },
  },
};

This is how it would look in any browser's console

Image of a screenshot

While if we try to log this within the Node runtime we would get something like

Screenshot

This problem can be solved with util.inspect that offers an API specifically for debugging nested objects.

const util = require(‘util’)
util.inspect(object, true, 4, true)

You can find more information here.