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.
Code
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: trueUnder 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:utilis 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
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.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Do I need to install anything before running this?
- Nothing needs installing: `node:util` ships with Node.js itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.