From dadd6e16888baac8fd110432b81f3fd1237be3e1 Mon Sep 17 00:00:00 2001 From: chocolateboy Date: Sun, 20 May 2018 21:27:34 +0100 Subject: 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 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 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) (limited to 'doc/api/util.md') diff --git a/doc/api/util.md b/doc/api/util.md index d67f46c043..d29fbfc5b7 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -574,9 +574,10 @@ terminals. -Objects may also define their own `[util.inspect.custom](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] function, +which `util.inspect()` will invoke and use the result of when inspecting +the object: ```js const util = require('util'); @@ -628,10 +629,41 @@ util.inspect(obj); ### util.inspect.custom -* {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