/

How to log an object in Node.js

How to log an object in Node.js

When it comes to logging objects in Node.js, things can be a bit trickier compared to doing so in a browser environment. The console.log() function in Node.js simply outputs the object as a string representation, which may not be ideal, especially for complex objects with nested properties.

By default, Node.js will print [Object] as a placeholder when an object goes beyond two levels of nesting. However, there are a couple of ways to overcome this limitation and log the object in a readable format.

One option is to use JSON.stringify() along with console.log(). This allows you to preserve the pretty print formatting by specifying the number of spaces to use for indentation. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const obj = {
name: 'Flavio',
age: 35,
person1: {
name: 'Tony',
age: 50,
person2: {
name: 'Albert',
age: 21,
person3: {
name: 'Peter',
age: 23
}
}
}
}
console.log(JSON.stringify(obj, null, 2));

The null parameter is used to filter out any properties you don’t want to include in the output.

Another option is to use the util.inspect() function from the Node.js util module. You can set the depth option to null to ensure that all nested objects are logged. However, be aware that this option may flatten the nested objects after the second level, which might be problematic for complex objects.

1
2
3
const util = require('util');
util.inspect.defaultOptions.depth = null;
console.log(obj);

By taking advantage of these techniques, you can log objects in Node.js in a more informative and readable way.

tags: [“Node.js”, “logging”, “object”, “JSON.stringify”, “util.inspect”]