From a2a1ebfecface85509faaecfc830e05bb4bfe8e3 Mon Sep 17 00:00:00 2001 From: chocolateboy Date: Sun, 20 May 2018 21:27:34 +0100 Subject: [PATCH] util: use a shared symbol for util.inspect.custom MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Define `util.inspect.custom` as `Symbol.for("nodejs.util.inspect.custom")` rather than `Symbol("util.inspect.custom")`. This allows `inspect` hooks to easily/safely be defined in non-Node.js environments. Fixes: https://github.com/nodejs/node/issues/20821 Refs: https://github.com/nodejs/node/pull/22684 Backport-PR-URL: https://github.com/nodejs/node/pull/23039 PR-URL: https://github.com/nodejs/node/pull/20857 Reviewed-By: Ruben Bridgewater Reviewed-By: Anna Henningsen Reviewed-By: Tiancheng "Timothy" Gu Reviewed-By: Sakthipriyan Vairamani Reviewed-By: James M Snell Reviewed-By: Matteo Collina Reviewed-By: Michaƫl Zasso Reviewed-By: John-David Dalton --- doc/api/util.md | 46 ++++++++++++++++++++++++++---- lib/internal/util.js | 2 +- test/parallel/test-assert.js | 2 +- test/parallel/test-console.js | 8 +++--- test/parallel/test-util-inspect.js | 28 ++++++++++++++---- 5 files changed, 69 insertions(+), 17 deletions(-) diff --git a/doc/api/util.md b/doc/api/util.md index 2b1e71100503d5..8dfbfd874c762a 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -572,9 +572,10 @@ terminals. -Objects may also define their own `[util.inspect.custom](depth, opts)` -(or the equivalent but deprecated `inspect(depth, opts)`) function that -`util.inspect()` will invoke and use the result of when inspecting the object: +Objects may also define their own +[`[util.inspect.custom](depth, opts)`][util.inspect.custom] (or the equivalent +but deprecated `inspect(depth, opts)`) function, which `util.inspect()` will +invoke and use the result of when inspecting the object: ```js const util = require('util'); @@ -626,10 +627,41 @@ util.inspect(obj); ### util.inspect.custom -A {symbol} that can be used to declare custom inspect functions, see -[Custom inspection functions on Objects][]. +* {symbol} that can be used to declare custom inspect functions. + +In addition to being accessible through `util.inspect.custom`, this +symbol is [registered globally][global symbol registry] and can be +accessed in any environment as `Symbol.for('nodejs.util.inspect.custom')`. + +```js +const inspect = Symbol.for('nodejs.util.inspect.custom'); + +class Password { + constructor(value) { + this.value = value; + } + + toString() { + return 'xxxxxxxx'; + } + + [inspect]() { + return `Password <${this.toString()}>`; + } +} + +const password = new Password('r0sebud'); +console.log(password); +// Prints Password +``` + +See [Custom inspection functions on Objects][] for more details. ### util.inspect.defaultOptions