Repository navigation
Feature request: utilize Symbol.toStringTag in util.inspect #12780
Description
Activity
- addedfeature requestIssues requesting new Node.js features.Issues requesting new Node.js features.utilIssues and PRs related to the built-in util module.Issues and PRs related to the built-in util module.
on May 1, 2017 Alternatively you can currently do:
[util.inspect.custom](depth, opts) { return this.type; }
Yes, the
util.inspect.custombit works, but given thatSymbol.toStringTagis a language standard, it should definitely be supported. That said, given thatutil.inspectis primarily intended as a debug mechanism, relying solely onSymbol.toStringTagmay be problematic. Perhaps a hybrid approach...class Foo { get [Symbol.toStringTag]() { return 'Bar'; } } var foo = new Foo(); console.log(foo); // Prints: Foo [@@toStringTag: Bar] { }
General +1 from me. I actually tinkered with this idea a few months ago in a branch that has been destroyed because of an HD failure, but I'm willing to write a new patch if needed.
Here are some of my findings:
What we currently do to find the class name is walking the prototype chain, and we use the
nameof the firstconstructorproperty we see that both a) is a function and b) has a non-emptyname. That brings up a few questions for@@toStringTagsupport:- Should we should look for
@@toStringTagas an own property first before walking the proto chain? - Should we prefer
@@toStringTagof a parent prototype over aconstructorproperty of a child prototype? If not, should we prefer@@toStringTagoverconstructorof the same prototype, or vice versa?
To 1 I'd answer yes, since that's also the choice taken by
Object.prototype.toString. To 2, I'd say no to the first, and yes to the second (so that@@toStringTagoverridesconstructorin the same prototype object, but not child prototypes). I'm not too big of a fan of @jasnell'sFoo [@@toStringTag: Bar] { }proposal. That's just a tad too busy, and I'd argue those who know of and set@@toStringTagprobably know what to expect through doing that.- Should we should look for
Weak -1. toStringTag is really meant just for Object.prototype.toString.call(), not for generic debugging output. The util hooks seem better for that.
But of course it's OK for debugging utils to take into account a large variety of signals, including ones not originally intended for debugging, so it's not a real problem.
This got implemented in #16956. Closing.
Sample usage is HTML tree, where every child node is named according to its type.
Example of print to console:
(edited by @vsemozhetbyt: added backticks for code blocks)