Browse Source

util: pass opts to custom inspect functions

Objects with custom inpsect functions should get the options that were
passed to `util.inspect()`

fixes #5822
fixes #6098
v0.11.7-release
Timothy J Fontaine 11 years ago
committed by isaacs
parent
commit
546ae2eef9
  1. 8
      doc/api/util.markdown
  2. 2
      lib/util.js
  3. 6
      test/simple/test-util-inspect.js

8
doc/api/util.markdown

@ -98,8 +98,8 @@ 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`.
- `customInspect` - if `false`, then custom `inspect(depth, opts)` functions
defined on the objects being inspected won't be called. Defaults to `true`.
Example of inspecting all properties of the `util` object:
@ -107,6 +107,10 @@ Example of inspecting all properties of the `util` object:
console.log(util.inspect(util, { showHidden: true, depth: null }));
Values may supply their own custom `inspect(depth, opts)` functions, when
called they receive the current depth in the recursive inspection, as well as
the options object passed to `util.inspect()`.
### Customizing `util.inspect` colors
<!-- type=misc -->

2
lib/util.js

@ -218,7 +218,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)) {
var ret = value.inspect(recurseTimes);
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}

6
test/simple/test-util-inspect.js

@ -161,6 +161,12 @@ subject.inspect = function() { return { foo: 'bar' }; };
assert.equal(util.inspect(subject), '{ foo: \'bar\' }');
subject.inspect = function(depth, opts) {
assert.strictEqual(opts.customInspectOptions, true);
};
util.inspect(subject, { customInspectOptions: true });
// util.inspect with "colors" option should produce as many lines as without it
function test_lines(input) {
var count_lines = function(str) {

Loading…
Cancel
Save