Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

util: custom inspect functions should receive opts #6098

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 6 additions & 2 deletions doc/api/util.markdown
Expand Up @@ -98,15 +98,19 @@ 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:

var util = require('util');

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 -->
Expand Down
2 changes: 1 addition & 1 deletion lib/util.js
Expand Up @@ -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);
}
Expand Down
6 changes: 6 additions & 0 deletions test/simple/test-util-inspect.js
Expand Up @@ -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) {
Expand Down