util.inspect Prints Nested Object Trees

Print nested objects with util.inspect using depth, compact, and breakLength options so log lines stay single-line and deep structures stay readable.

JavascriptCli Tooling

Code

javascriptsnippet
15 lines
import { inspect } from 'node:util';

const task = {
  id: 7,
  tags: ['cache', 'slow'],
  meta: { attempts: 2, lastError: null },
  run: () => 'noop',
};

console.log(inspect(task, { depth: 1 }));
console.log(inspect(task, { depth: 0, breakLength: Infinity }));

// compact single-line form for structured logs
console.log(inspect(task, { compact: true, breakLength: Infinity, depth: Infinity }));
console.log('deep fields hidden at depth 0:', !inspect(task, { depth: 0 }).includes('lastError'));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

{
  id: 7,
  tags: [ 'cache', 'slow' ],
  meta: { attempts: 2, lastError: null },
  run: [Function: run]
}
{ id: 7, tags: [Array], meta: [Object], run: [Function: run] }
{ id: 7, tags: [ 'cache', 'slow' ], meta: { attempts: 2, lastError: null }, run: [Function: run] }
deep fields hidden at depth 0: true

How the snippet works

node:util supplies inspect — built-in surface, no package involved.

The demo data lives in module-level bindings: task.

Points of care

  • The dependency surface is just node:util, and that one is built into Node.js.

Applying it to real inputs

The demo output is labeled (deep fields hidden at depth 0:), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The imports resolve to Node.js core modules, which the runtime provides.