Permalink
Browse files

util: add a "customInspect" option to `util.inspect()`

For disabling calling the custom `inspect()` function when defined on an object
that is being inspected.
  • Loading branch information...
1 parent 07774e6 commit 4c46f5833d0857db742af78ebdaa8ce6d0975536 @TooTallNate committed Oct 10, 2012
Showing with 13 additions and 1 deletion.
  1. +3 −0 doc/api/util.markdown
  2. +2 −1 lib/util.js
  3. +8 −0 test/simple/test-util-inspect.js
View
3 doc/api/util.markdown
@@ -83,6 +83,9 @@ formatted string:
- `colors` - if `true`, then the output will be styled with ANSI color codes.
Defaults to `false`. Colors are customizable, see below.
+ - `customInspect` - if `false`, then custom `inspect()` functions defined on the
+ objects being inspected won't be called. Defaults to `true`.
+
Example of inspecting all properties of the `util` object:
var util = require('util');
View
3 lib/util.js
@@ -132,6 +132,7 @@ function inspect(obj, opts/* legacy: showHidden, depth, colors*/) {
if (typeof ctx.showHidden === 'undefined') ctx.showHidden = false;
if (typeof ctx.depth === 'undefined') ctx.depth = 2;
if (typeof ctx.colors === 'undefined') ctx.colors = false;
+ if (typeof ctx.customInspect === 'undefined') ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
@@ -200,7 +201,7 @@ function arrayToHash(array) {
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
- if (value && typeof value.inspect === 'function' &&
+ if (ctx.customInspect && value && typeof value.inspect === 'function' &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
View
8 test/simple/test-util-inspect.js
@@ -149,3 +149,11 @@ assert(util.inspect(subject, { colors: true }).indexOf('\u001b[32m') !== -1);
assert(util.inspect(subject, { depth: 2 }).indexOf('c: [Object]') !== -1);
assert(util.inspect(subject, { depth: 0 }).indexOf('a: [Object]') !== -1);
assert(util.inspect(subject, { depth: null }).indexOf('{ d: 0 }') !== -1);
+
+// "customInspect" option can enable/disable calling inspect() on objects
+subject = { inspect: function() { return 123; } };
+
+assert(util.inspect(subject, { customInspect: true }).indexOf('123') !== -1);
+assert(util.inspect(subject, { customInspect: true }).indexOf('inspect') === -1);
+assert(util.inspect(subject, { customInspect: false }).indexOf('123') === -1);
+assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1);

1 comment on commit 4c46f58

Please sign in to comment.