Skip to content
jshacks.dev
Node.js

util.inspect() in Node.js Explained

See how util.inspect turns any value into readable text in Node.js 24 and 26: depth, sorting, array limits, circular references and custom inspect methods.

7 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the Node.js, Vite, JavaScript and npm logos.

Every time you call console.log() on an object, Node.js passes it through util.inspect() first. That function decides how deep to go into nested objects, where to break lines, how to show a class instance, a Map or a circular reference, and when to give up and print [Object]. Most developers meet it through its surprises: a nested object printed as [Object], an array cut short with ... 100 more items, a class that logs as Foo {}. This post explains util.inspect() on Node.js 24 and 26, the options that change its output, and the symbol that lets your own classes control how they print. It sits next to util.format(), which calls it for the %o and %O placeholders, and util.types(). Every sample shows its exact output.

What util.inspect returns

util.inspect(value, options) returns a string. It never prints anything on its own, which makes it useful for logging, error messages and tests. The string is meant for humans, not for parsing, so do not use it as a serialization format. The util documentation states that the exact output can change between Node.js versions.

inspect-basic.mjsJavaScript
import { inspect } from "node:util";

class User {
  constructor(name) {
    this.name = name;
  }
}

console.log(inspect("it's"));
console.log(inspect("a"));
console.log(inspect(new User("Ada")));
console.log(inspect(new Map([["a", 1], ["b", 2]])));
console.log(inspect(new Set([1, 2, 3])));
console.log(inspect([1, "two", null, undefined]));
Text
"it's"
'a'
User { name: 'Ada' }
Map(2) { 'a' => 1, 'b' => 2 }
Set(3) { 1, 2, 3 }
[ 1, 'two', null, undefined ]

Three habits show up here. Strings are quoted, and the quote style changes to double quotes when the text itself contains a single quote, so the output stays valid as a literal. Class instances carry their constructor name. Collections show their size in brackets before the contents. A reader who knows these conventions can tell a Map from a plain object and a User from an anonymous record at a glance.

Controlling depth

By default, inspect descends two levels into nested objects and replaces anything deeper with [Object] or [Array]. This is the origin of the most common complaint about console.log.

inspect-depth.mjsJavaScript
import { inspect } from "node:util";

const tree = { a: { b: { c: { d: 1 } } } };

console.log(inspect(tree));
console.log(inspect(tree, { depth: 0 }));
console.log(inspect(tree, { depth: 1 }));
Text
{ a: { b: { c: [Object] } } }
{ a: [Object] }
{ a: { b: [Object] } }

The top-level object is level zero, so with depth: 0 you see its own keys and nothing below them. Setting depth: null removes the limit, which is handy for a one-off look at a deeply nested response but risky on huge structures, because the output can be enormous. Passing Infinity has the same effect.

You can set the limit for console.log itself with util.inspect.defaultOptions.depth = 4, though changing a global default affects every log line in the process, including those written by libraries. For a single call, console.dir(value, { depth: null }) takes the same options and is usually the better tool at a debugging session.

Sorting, limits and line breaks

Several options deal with the size and shape of the output.

inspect-options.mjsJavaScript
import { inspect } from "node:util";

const config = { zeta: 1, alpha: 2, mid: 3 };
console.log(inspect(config, { sorted: true }));

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(inspect(numbers, { maxArrayLength: 3 }));

const text = "abcdefghij";
console.log(inspect(text, { maxStringLength: 4 }));

const nested = { id: 7, tags: ["a", "b"] };
console.log(inspect(nested, { compact: false }));
console.log(inspect(nested, { breakLength: Infinity }));
Text
{ alpha: 2, mid: 3, zeta: 1 }
[ 1, 2, 3, ... 7 more items ]
'abcd'... 6 more characters
{
  id: 7,
  tags: [
    'a',
    'b'
  ]
}
{ id: 7, tags: [ 'a', 'b' ] }

sorted: true orders keys alphabetically, which makes output stable for snapshots and diffs. maxArrayLength limits how many array, Set and Map entries print, and the rest is summarized. maxStringLength does the same for string length. The compact option controls how aggressively short objects are joined onto one line: the default is 3, meaning an object that contains at most three levels of inner nesting stays on one line when it fits, and false puts every property on its own line. breakLength is the width at which lines are broken, 80 by default, and Infinity keeps everything on one line.

Other options worth knowing:

  • showHidden: true also prints non-enumerable properties and, for some built-ins, internal slots.

  • getters: true evaluates getter properties and prints their values rather than [Getter].

  • colors: true adds ANSI color codes, which console.log already turns on in a terminal.

  • numericSeparator: true prints large numbers such as 1_000_000 with underscores.

  • showProxy: true shows the target and handler of a proxy instead of inspecting through it.

Circular references

An object that refers to itself would make a naive printer loop forever. inspect detects the cycle and marks it.

inspect-circular.mjsJavaScript
import { inspect } from "node:util";

const node = { name: "loop" };
node.self = node;

console.log(inspect(node));
Text
<ref *1> { name: 'loop', self: [Circular *1] }

The <ref *1> label tags the object that is the target of the cycle, and [Circular *1] marks the place where it comes back. If there are several cycles, they get different numbers. This is also why JSON.stringify throws on the same object while console.log does not: inspect is built to describe, and JSON.stringify is built to serialize.

Controlling how your own classes print

An object can take over its own representation by defining a method under the symbol util.inspect.custom. Node.js calls it with the remaining depth, the resolved options and the inspect function itself, and uses the return value in place of the default output.

inspect-custom.mjsJavaScript
import { inspect } from "node:util";

class Money {
  constructor(amount, currency) {
    this.amount = amount;
    this.currency = currency;
  }

  [inspect.custom](depth, options, inspectFn) {
    return `Money<${this.amount} ${this.currency}>`;
  }
}

const price = new Money(5, "EUR");
console.log(price);
console.log({ item: "book", price });
console.log(inspect(price));
Text
Money<5 EUR>
{ item: 'book', price: Money<5 EUR> }
Money<5 EUR>

The same custom method is used when the object is nested inside another one and when it is passed to console.log directly, because both go through inspect. The symbol is registered globally as Symbol.for("nodejs.util.inspect.custom"), so a library can implement it without importing node:util at all, which is how many packages add readable output without a dependency.

When the custom method returns a string, that string is used as is. When it returns anything else, Node.js inspects the returned value. That second route is useful for hiding fields: return a copy of the object without a secret, and the secret never reaches your logs.

inspect-redact.mjsJavaScript
import { inspect } from "node:util";

class Session {
  constructor(user, token) {
    this.user = user;
    this.token = token;
  }

  [inspect.custom]() {
    return { user: this.user, token: "[hidden]" };
  }
}

console.log(new Session("ada", "s3cret-value"));
Text
{ user: 'ada', token: '[hidden]' }

Notice that the class name is gone, because the returned value is a plain object. If you want the name back, build the string yourself, or return a new instance of a small helper class with the same name. Redaction through the inspect hook protects logs written with console.log, but not output from JSON.stringify, so treat it as one layer and not the whole defense for secrets.

util.inspect compared with JSON.stringify

The two functions look similar and serve different jobs. JSON.stringify produces data another program can read back. It drops undefined, functions and symbols, turns NaN into null, and throws on cycles and on BigInt. util.inspect produces text for a person. It keeps undefined, shows functions as [Function: name], prints Map and Set contents, and survives cycles. If a log line is for a human, use inspect or console.log. If it is for a machine, use JSON. Mixing them is how logs end up with [object Object] or silently missing fields.

Where inspect appears without you calling it

You rarely call util.inspect directly, because it sits behind several everyday tools:

  • console.log, console.error and friends format non-string arguments with it.

  • console.dir(value, options) passes its options straight through.

  • The placeholders %o and %O in format strings use it, as covered in the post on util.format().

  • The Node.js REPL uses it to print results.

  • Uncaught error output and assert failure messages use it to show values.

That reach is why setting util.inspect.defaultOptions is a blunt tool. A change made in one module alters how every other module's logs look for the rest of the process. Prefer passing options per call, or wrap them in a small helper such as const show = (v) => inspect(v, { depth: null, sorted: true }).

Practical rules

  • Use console.dir(obj, { depth: null }) when you only want to see everything once.

  • Add a util.inspect.custom method to value classes so logs show something meaningful instead of a dump of fields.

  • Keep secrets out of logged objects by design. A custom inspect method is a safety net, not a policy.

  • Do not parse the output of inspect. Its format is for reading and can change between releases.

  • Set a maxArrayLength and maxStringLength when logging data of unknown size, so one large payload does not flood a log.

These options behave the same on Node.js 24 and Node.js 26, the LTS line since October 2026, and on the Node.js 22 maintenance line.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.