Home >Web Front-end >JS Tutorial >How to Display Full Objects in Node.js's `console.log()`?

How to Display Full Objects in Node.js's `console.log()`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 12:28:11970browse

How to Display Full Objects in Node.js's `console.log()`?

How to Get the Full Object in Node.js's console.log()

When inspecting objects in Node.js using console.log(), it is common to encounter the '[Object]' placeholder instead of the full object representation. This occurs when an object has nested properties that extend beyond the default inspection depth.

The Solution: util.inspect()

To overcome this limitation, use the util.inspect() function. This function allows for in-depth object inspection and customization of the output.

To get the full object, pass it as the first parameter to util.inspect():

const util = require('util');

console.log(util.inspect(myObject));

Customizing the Output

You can further customize the output by passing additional options to inspect():

  • showHidden: Whether to display non-enumerable properties (defaults to false)
  • depth: The maximum depth to traverse the object (defaults to 2)
  • colors: Whether to use colors in the output (defaults to false)

For example, to disable the display of hidden properties and enable colors:

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

Alternative Syntax

As a shortcut, you can also pass a boolean value as the second parameter to util.inspect() to specify whether to enable colors:

console.log(util.inspect(myObject, true)); // enables colors

Using util.inspect() provides a convenient way to get the full object representation in Node.js's console.log(), making object inspection more informative and easier to debug.

The above is the detailed content of How to Display Full 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