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

Closed
wants to merge 3 commits into from
View
14 doc/api/util.markdown
@@ -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)
View
3 lib/util.js
@@ -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));
@@ -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
View
13 test/simple/test-util-inspect.js
@@ -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);