inspect.custom Shapes Console Output

Define an [inspect.custom] method and console.log prints your business shape instead of the default object dump — fields stay untouched.

JavascriptCli Tooling

Code

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

class Money {
  constructor(cents) {
    this.cents = cents;
  }

  // console.log and util.inspect print this string for the instance
  [inspect.custom]() {
    return `Money<${(this.cents / 100).toFixed(2)} USD>`;
  }
}

const price = new Money(4200);
console.log(price);
console.log(inspect(price));
console.log('inspect matches:', inspect(price) === 'Money<42.00 USD>');
console.log('fields intact:', price.cents === 4200);

Output

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

Money<42.00 USD>
Money<42.00 USD>
inspect matches: true
fields intact: true

Under the hood

The snippet is organized around the class Money.

The import names the platform contact area: inspect, all from node:util.

Top-level bindings price hold the demo state — nothing sits inside a function scope.

Points of care

  • node:util is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Putting it to use

Watch the output for labels — inspect matches:, fields intact: — when the file runs.

Core lines

return `Money<${(this.cents / 100).toFixed(2)} USD>`;

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Nothing needs installing: `node:util` ships with Node.js itself.