Logo

How can I get the full object in Node.js's console.log()?

By default, console.log() may truncate or simplify large or deeply nested objects to keep the output concise. If you need a more complete or expanded view, try one of the following approaches:

1. Use console.dir with Custom Options

console.dir() is similar to console.log(), but it provides options to control the depth and formatting:

const obj = { /* deeply nested object */ }; console.dir(obj, { depth: null, colors: true });
  • depth: null tells Node.js to display all nested levels (instead of truncating).
  • colors: true enables syntax highlighting in many terminals, making objects easier to read.

2. Use util.inspect

The built-in util module allows you to customize inspection. For instance:

const util = require('util'); const obj = { /* deeply nested object */ }; console.log(util.inspect(obj, { showHidden: false, depth: null, colors: true }));
  • depth: null again means no limit on nesting.
  • colors: true turns on colored output.

3. Convert to JSON String

For a straightforward textual representation (without color or special formatting):

const obj = { /* deeply nested object */ }; console.log(JSON.stringify(obj, null, 2));
  • JSON.stringify converts the object into a JSON string.
  • null is for the replacer argument (unused here).
  • 2 adds indentation for readability.

Note: This can fail if the object contains circular references.

Recommended Resource

Best Practices

  • Choose the right tool: If you need a quick snapshot, console.log() might suffice. For deep debugging of nested structures, consider console.dir() or util.inspect() with depth: null.
  • Watch out for performance: Very large objects or circular references can cause performance overhead or errors when stringifying. Use carefully, especially in production code.
  • Use in development: These methods are usually for debugging and not typically used in final production logs.

With these approaches, you can see the entire structure of your objects in Node.js without truncation or missing details.

CONTRIBUTOR
TechGrind