Skip to content

Commit 97dfced

Browse files
Havvyaddaleax
authored andcommitted
doc: 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. Ref: #8442 PR-URL: #8875 Reviewed-By: Evan Lucas <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Anna Henningsen <[email protected]>
1 parent 366fc7a commit 97dfced

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

doc/api/util.md

+24-6
Original file line numberDiff line numberDiff line change
@@ -286,13 +286,31 @@ invoke and use the result of when inspecting the object:
286286
```js
287287
const util = require('util');
288288

289-
const obj = { name: 'nate' };
290-
obj[util.inspect.custom] = function(depth) {
291-
return `{${this.name}}`;
292-
};
289+
class Box {
290+
constructor(value) {
291+
this.value = value;
292+
}
293293

294-
util.inspect(obj);
295-
// "{nate}"
294+
inspect(depth, options) {
295+
if (depth < 0) {
296+
return options.stylize('[Box]', 'special');
297+
}
298+
299+
const newOptions = Object.assign({}, options, {
300+
depth: options.depth === null ? null : options.depth - 1
301+
});
302+
303+
// Five space padding because that's the size of "Box< ".
304+
const padding = ' '.repeat(5);
305+
const inner = util.inspect(this.value, newOptions).replace(/\n/g, '\n' + padding);
306+
return options.stylize('Box', 'special') + '< ' + inner + ' >';
307+
}
308+
}
309+
310+
const box = new Box(true);
311+
312+
util.inspect(box);
313+
// "Box< true >"
296314
```
297315

298316
Custom `[util.inspect.custom](depth, opts)` functions typically return a string

0 commit comments

Comments
 (0)