Skip to content

Commit f17e7d2

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: nodejs#8174 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Michaël Zasso <mic.besace@gmail.com>
1 parent 55906f9 commit f17e7d2

2 files changed

Lines changed: 18 additions & 3 deletions

File tree

lib/util.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -255,10 +255,15 @@ function formatValue(ctx, value, recurseTimes) {
255255
// Also filter out any prototype objects using the circular check.
256256
!(value.constructor && value.constructor.prototype === value)) {
257257
let ret = maybeCustomInspect.call(value, recurseTimes, ctx);
258-
if (typeof ret !== 'string') {
259-
ret = formatValue(ctx, ret, recurseTimes);
258+
259+
// If the custom inspection method returned `this`, don't go into
260+
// infinite recursion.
261+
if (ret !== value) {
262+
if (typeof ret !== 'string') {
263+
ret = formatValue(ctx, ret, recurseTimes);
264+
}
265+
return ret;
260266
}
261-
return ret;
262267
}
263268
}
264269

test/parallel/test-util-inspect.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,16 @@ assert.doesNotThrow(function() {
387387
);
388388
}
389389

390+
{
391+
// Returning `this` from a custom inspection function works.
392+
assert.strictEqual(util.inspect({ a: 123, inspect() { return this; } }),
393+
'{ a: 123, inspect: [Function: inspect] }');
394+
395+
const subject = { a: 123, [util.inspect.custom]() { return this; } };
396+
assert.strictEqual(util.inspect(subject),
397+
'{ a: 123 }');
398+
}
399+
390400
// util.inspect with "colors" option should produce as many lines as without it
391401
function test_lines(input) {
392402
var count_lines = function(str) {

0 commit comments

Comments
 (0)