Skip to content

Commit a60ed89

Browse files
committed
util: allow returning this from custom inspect
If a custom inspection function returned `this`, use that value for further formatting instead of going into infinite recursion. This is particularly useful when combined with `util.inspect.custom` because returning `this` from such a method makes it easy to have an `inspect()` function that is ignored by `util.inspect` without actually having to provide an alternative for custom inspection. PR-URL: #8174 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Michaël Zasso <[email protected]>
1 parent 59714cb commit a60ed89

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

lib/util.js

+8-3
Original file line numberDiff line numberDiff line change
@@ -362,10 +362,15 @@ function formatValue(ctx, value, recurseTimes) {
362362
// Also filter out any prototype objects using the circular check.
363363
!(value.constructor && value.constructor.prototype === value)) {
364364
let ret = maybeCustomInspect.call(value, recurseTimes, ctx);
365-
if (typeof ret !== 'string') {
366-
ret = formatValue(ctx, ret, recurseTimes);
365+
366+
// If the custom inspection method returned `this`, don't go into
367+
// infinite recursion.
368+
if (ret !== value) {
369+
if (typeof ret !== 'string') {
370+
ret = formatValue(ctx, ret, recurseTimes);
371+
}
372+
return ret;
367373
}
368-
return ret;
369374
}
370375
}
371376

test/parallel/test-util-inspect.js

+10
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,16 @@ assert.doesNotThrow(function() {
567567
);
568568
}
569569

570+
{
571+
// Returning `this` from a custom inspection function works.
572+
assert.strictEqual(util.inspect({ a: 123, inspect() { return this; } }),
573+
'{ a: 123, inspect: [Function: inspect] }');
574+
575+
const subject = { a: 123, [util.inspect.custom]() { return this; } };
576+
assert.strictEqual(util.inspect(subject),
577+
'{ a: 123 }');
578+
}
579+
570580
// util.inspect with "colors" option should produce as many lines as without it
571581
function test_lines(input) {
572582
var count_lines = function(str) {

0 commit comments

Comments
 (0)