util: add inspect.defaultOptions by silverwind · Pull Request #8013 · nodejs/node · GitHub
Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions doc/api/util.md
42 changes: 27 additions & 15 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,16 @@ const internalUtil = require('internal/util');
const binding = process.binding('util');

const isError = internalUtil.isError;
const kDefaultMaxLength = 100;

const inspectDefaultOptions = Object.seal({
showHidden: false,
depth: 2,
colors: false,
customInspect: true,
showProxy: false,
maxArrayLength: 100,
breakLength: 60
});

var Debug;
var simdFormatters;
Expand Down Expand Up @@ -176,29 +185,31 @@ function inspect(obj, opts) {
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (arguments[2] !== undefined) ctx.depth = arguments[2];
if (arguments[3] !== undefined) ctx.colors = arguments[3];
if (typeof opts === 'boolean') {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (ctx.showHidden === undefined) ctx.showHidden = false;
if (ctx.depth === undefined) ctx.depth = 2;
if (ctx.colors === undefined) ctx.colors = false;
if (ctx.customInspect === undefined) ctx.customInspect = true;
if (ctx.showProxy === undefined) ctx.showProxy = false;
// Set default and user-specified options
ctx = Object.assign({}, inspect.defaultOptions, ctx, opts);
if (ctx.colors) ctx.stylize = stylizeWithColor;
if (ctx.maxArrayLength === undefined) ctx.maxArrayLength = kDefaultMaxLength;
if (ctx.maxArrayLength === null) ctx.maxArrayLength = Infinity;
if (ctx.breakLength === undefined) ctx.breakLength = 60;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;

Object.defineProperty(inspect, 'defaultOptions', {
get: function() {
return inspectDefaultOptions;
},
set: function(options) {
if (options === null || typeof options !== 'object') {
throw new TypeError('"options" must be an option');
}
Object.assign(inspectDefaultOptions, options);
return inspectDefaultOptions;
}
});

// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
Expand Down Expand Up @@ -231,6 +242,7 @@ inspect.styles = {
'regexp': 'red'
};

exports.inspect = inspect;

function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
Expand Down
41 changes: 41 additions & 0 deletions test/parallel/test-util-inspect.js