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.
Code
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: trueHow 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.
FAQ
- Are there third-party dependencies?
- No. The imports resolve to Node.js core modules, which the runtime provides.
Report a problem with this exampleOpens a pre-filled issue on GitHub.