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
Release: 2024-12-09 19:42:21
Original
195 people have browsed it

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"
        }
      }
    }
  }
};
Copy after login

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] } } }
Copy after login

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 }));
Copy after login

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' } } } } }
Copy after login

An alternative shorthand method that yields the same result:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template