How to log an object in Node
Logging objects in Node.js
When you type console.log()
into a JavaScript program that runs in the browser, that is going to create a nice entry in the Browser Console:
Once you click the arrow, the log is expanded, and you can clearly see the object properties:
In Node, the same happens.
We donโt have such luxury when we log something to the console, because thatโs going to output the object to the shell if you run the Node program manually, or to the log file. You get a string representation of the object.
Now, all is fine until a certain level of nesting. After two levels of nesting, Node gives up and prints [Object]
as a placeholder:
const obj = {
name: 'Flavio',
age: 35,
person1: {
name: 'Tony',
age: 50,
person2: {
name: 'Albert',
age: 21,
person3: {
name: 'Peter',
age: 23
}
}
}
}
console.log(obj)
{
name: 'Flavio',
age: 35,
person1: {
name: 'Tony',
age: 50,
person2: {
name: 'Albert',
age: 21,
person3: [Object]
}
}
}
How can you print the whole object?
The best way to do so, while preserving the pretty print, is to use
console.log(JSON.stringify(obj, null, 2))
where 2
is the number of spaces to use for indentation.
Another option is to use
require('util').inspect.defaultOptions.depth = null
console.log(obj)
but the problem is that the nested objects after level 2 are now flattened, and this might be a problem with complex objects.
THE VALLEY OF CODE
THE WEB DEVELOPER's MANUAL
You might be interested in those things I do:
- Learn to code in THE VALLEY OF CODE, your your web development manual
- Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
- I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
- Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
- Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
- Find me on X