Skip to content

Pass util.inspect to custom inspect methods #35956

Description

@Jamesernator

Currently when using [Symbol.for('nodejs.util.inspect.custom')](depth, opts) in cross-environment code we have a problem when wanting to use the results of util.inspect on inner values of our value.

For example consider an implementation of Complex like so:

classComplex{
#real;
#imag;constructor(real,imag){this.#real =real;this.#imag =imag;}getreal(){returnthis.#real;}getimag(){returnthis.#imag;}}

If we wish to extend it with [Symbol.for('nodejs.util.custom.inspect')] we can do something like the following:

classComplex{// ...[Symbol.for('nodejs.util.inspect.custom')](){return`Complex { real: ${this.#real }, imag: ${this.#imag } }`}}

However this has the downside of losing the color-formatting on the numbers. In order to fix this we could import util.inspect and use it as follows:

import{inspect}from'util';classComplex{// ...[Symbol.for('nodejs.util.inspect.custom')](){return`Complex { real: ${inspect(this.#real)}, imag: ${inspect(this.#imag)} }`}}

However now we have made our code non-portable by importing util, even though this code has no other dependencies on Node.

As such I'd like to propose passing inspect into [Symbol.for('nodejs.util.inspect.custom')]() as the third argument so that we could write it like so:

classComplex{// ...[Symbol.for('nodejs.util.inspect.custom')](depth,opts,inspect){return`Complex { real: ${inspect(this.#real)}, imag: ${inspect(this.#imag)} }`;}

Metadata

Metadata

Assignees

No one assigned

    Labels

    utilIssues and PRs related to the built-in util module.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions