Browse Source

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

For disabling calling the custom `inspect()` function when defined on an object
that is being inspected.
v0.9.3-release
Nathan Rajlich 12 years ago
parent
commit
4eb5399bb2
  1. 3
      doc/api/util.markdown
  2. 3
      lib/util.js
  3. 8
      test/simple/test-util-inspect.js

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');

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.

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);

Loading…
Cancel
Save