diff --git a/doc/api/util.md b/doc/api/util.md index 295c1d984e2200..a39d372c294d61 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -187,6 +187,9 @@ stream.write('It works!'); // Received data: "It works!" `TypedArray` elements to include when formatting. Defaults to `100`. Set to `null` to show all array elements. Set to `0` or negative to show no array elements. + * `breakLength` {number} The length at which an object's keys are split + across multiple lines. Set to `Infinity` to format an object as a single + line. Defaults to 60 for legacy compatibility. The `util.inspect()` method returns a string representation of `object` that is primarily useful for debugging. Additional `options` may be passed that alter diff --git a/lib/util.js b/lib/util.js index 833659f313f73a..d4b87eaeb0a58f 100644 --- a/lib/util.js +++ b/lib/util.js @@ -194,6 +194,7 @@ function inspect(obj, 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; @@ -575,7 +576,7 @@ function formatValue(ctx, value, recurseTimes) { ctx.seen.pop(); - return reduceToSingleString(output, base, braces); + return reduceToSingleString(output, base, braces, ctx.breakLength); } @@ -807,12 +808,12 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { } -function reduceToSingleString(output, base, braces) { +function reduceToSingleString(output, base, braces, breakLength) { var length = output.reduce(function(prev, cur) { return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); - if (length > 60) { + if (length > breakLength) { return braces[0] + // If the opening "brace" is too large, like in the case of "Set {", // we need to force the first item to be on the next line or the diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index ee009720211c59..68f8a228b81ac3 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -709,3 +709,16 @@ checkAlignment(new Map(big_array.map(function(y) { return [y, null]; }))); const x = new Uint8Array(101); assert(!/1 more item/.test(util.inspect(x, {maxArrayLength: Infinity}))); } + +{ + const obj = {foo: 'abc', bar: 'xyz'}; + const oneLine = util.inspect(obj, {breakLength: Infinity}); + // Subtract four for the object's two curly braces and two spaces of padding. + // Add one more to satisfy the strictly greater than condition in the code. + const breakpoint = oneLine.length - 5; + const twoLines = util.inspect(obj, {breakLength: breakpoint}); + + assert.strictEqual(oneLine, '{ foo: \'abc\', bar: \'xyz\' }'); + assert.strictEqual(oneLine, util.inspect(obj, {breakLength: breakpoint + 1})); + assert.strictEqual(twoLines, '{ foo: \'abc\',\n bar: \'xyz\' }'); +}