Home >Web Front-end >JS Tutorial >How Can I Fully Inspect Complex Objects in Node.js's console.log()?

How Can I Fully Inspect Complex Objects in Node.js's console.log()?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 19:42:21190browse

How Can I Fully Inspect Complex Objects in Node.js's console.log()?

Retrieve the Full Object in Node.js's console.log()

When working with complex objects in Node.js, it's often inconvenient to encounter the enigmatic "[Object]" placeholder in the console output. To reveal the entire object structure, including nested values, the solution lies in leveraging the util.inspect() method.

To illustrate, consider the following object:

const myObject = {
  "a": "a",
  "b": {
    "c": "c",
    "d": {
      "e": "e",
      "f": {
        "g": "g",
        "h": {
          "i": "i"
        }
      }
    }
  }
};

When logged to the console using console.log(myObject), the output is truncated, displaying only the first level of properties:

{ a: 'a', b: { c: 'c', d: { e: 'e', f: [Object] } } }

To bypass this limitation and retrieve the full object, we employ util.inspect():

const util = require('util')

console.log(util.inspect(myObject, { showHidden: false, depth: null, colors: true }));

This command produces a comprehensive output, revealing all the nested values:

{ a: 'a',  b: { c: 'c', d: { e: 'e', f: { g: 'g', h: { i: 'i' } } } } }

An alternative shorthand method that yields the same result:

console.log(util.inspect(myObject, false, null, true)); // enable colors

By utilizing util.inspect(), you gain the ability to delve into the intricacies of your objects, revealing their complete structure right in the console.

The above is the detailed content of How Can I Fully Inspect Complex Objects in Node.js's console.log()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn