From 546ae2eef90c4ef0eb30ef4f52402e3c45e2f3f2 Mon Sep 17 00:00:00 2001 From: Timothy J Fontaine Date: Wed, 21 Aug 2013 18:38:23 -0700 Subject: [PATCH] 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 --- doc/api/util.markdown | 8 ++++++-- lib/util.js | 2 +- test/simple/test-util-inspect.js | 6 ++++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/doc/api/util.markdown b/doc/api/util.markdown index 88ef5eae030..96940dac56c 100644 --- a/doc/api/util.markdown +++ b/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 diff --git a/lib/util.js b/lib/util.js index 78c16a51204..9901a66a0ec 100644 --- a/lib/util.js +++ b/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); } diff --git a/test/simple/test-util-inspect.js b/test/simple/test-util-inspect.js index 8c894566f72..132726b1bcb 100644 --- a/test/simple/test-util-inspect.js +++ b/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) {