Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Pass the 'showHidden' and 'colors' params along to custom inspect() functions #2443

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions doc/api/util.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,20 @@ Example of inspecting all properties of the `util` object:

console.log(util.inspect(util, true, null));

Custom objects may also define their own `inspect()` function, to output a custom
representation of the object. The function will be invoked when the object has
`inspect` called on it. The arguments passed to the function are in the order:
`depth`, `showHidden`, and `colors`:

var util = require('util');

var o = {}
o.inspect = function (depth, showHidden, colors) {
return util.inspect('custom output', showHidden, depth, colors);
}

console.log(util.inspect(o, false, null, true));


### util.isArray(object)

Expand Down
3 changes: 2 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ function inspect(obj, showHidden, depth, colors) {
var ctx = {
showHidden: showHidden,
seen: [],
colors: colors,
stylize: colors ? stylizeWithColor : stylizeNoColor
};
return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth));
Expand Down Expand Up @@ -158,7 +159,7 @@ function formatValue(ctx, value, recurseTimes) {
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
return value.inspect(recurseTimes);
return value.inspect(recurseTimes, ctx.showHidden, ctx.colors);
}

// Primitive types cannot have properties
Expand Down
13 changes: 13 additions & 0 deletions test/simple/test-util-inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,16 @@ assert.doesNotThrow(function () {
// GH-2225
var x = { inspect: util.inspect };
assert.ok(util.inspect(x).indexOf('inspect') != -1);

// test for custom inspect() functionality
var o = { foo: 'bar' };
var inspectCalled = false;
o.inspect = function (d, h, c) {
inspectCalled = true;
assert.equal(d, 10);
assert.equal(h, false);
assert.equal(c, true);
return this.foo;
}
assert.equal(util.inspect(o, false, 10, true), 'bar');
assert.ok(inspectCalled);