From bc57bc843b5420650f60a8f3fff111cc1c91adb3 Mon Sep 17 00:00:00 2001 From: "Ryan Scheel (Havvy)" Date: Sat, 1 Oct 2016 00:56:16 +0000 Subject: [PATCH 1/2] docs: more realistic custom inspect example Changes the custom inspect example to a more complex object that actually uses the parameters of the custom inspect function. I specifically chose a wrapper of a value called a "Box" that inspects to "Box < inner_inspect_value >". I also want there to be documentation explaining what the code is actually doing. E.g., the padding replacement part is to make the inspected value line up properly when multi-line inputs are given. I also went with having a space between the Box's brackets and the inner value because it matches how objects work, and that should definitely be listed as a convention somewhere in here. Also, the convention to shorten only when depth is less than 0, not e.g. at 0. But I don't know how to write the documentation for that, so I'm leaving that to somebody who reads this message. Partially fixes: https://github.com/nodejs/node/issues/8442 --- doc/api/util.md | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/doc/api/util.md b/doc/api/util.md index 3ffefa3f87fe31..52a19f19b8ef40 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -286,13 +286,31 @@ invoke and use the result of when inspecting the object: ```js const util = require('util'); -const obj = { name: 'nate' }; -obj[util.inspect.custom] = function(depth) { - return `{${this.name}}`; -}; +class Box { + constructor(value) { + this.value = value; + } -util.inspect(obj); - // "{nate}" + inspect(depth, options) { + if (depth < 0) { + return options.stylize('[Box]', 'special'); + } + + const newOptions = Object.assign({}, options, { + depth: options.depth === null ? null : options.depth - 1 + }); + + // Five space padding because that's the size of "Box< ". + const padding = ' '; + const inner = util.inspect(this.value, newOptions).replace(/\n/g, '\n' + padding); + return options.stylize('Box', 'special') + '< ' + inner + ' >'; + } +} + +const box = new Box(true); + +util.inspect(box); + // "Box< true >" ``` Custom `[util.inspect.custom](depth, opts)` functions typically return a string From ad9ef926e46336ba5aed887067e1a5724899e379 Mon Sep 17 00:00:00 2001 From: "Ryan Scheel (Havvy)" Date: Sun, 2 Oct 2016 03:14:56 +0000 Subject: [PATCH 2/2] use " ".repeat in custom util.inspect example --- doc/api/util.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/util.md b/doc/api/util.md index 52a19f19b8ef40..57ed7269f68b87 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -301,7 +301,7 @@ class Box { }); // Five space padding because that's the size of "Box< ". - const padding = ' '; + const padding = ' '.repeat(5); const inner = util.inspect(this.value, newOptions).replace(/\n/g, '\n' + padding); return options.stylize('Box', 'special') + '< ' + inner + ' >'; }