util: change inspect compact and breakLength default

This changes the `compact` default from `true` to `3`. That mode
changes arrays to be grouped together, it alignes multiple small
entries on a single line in similar to `compact` true but only for
the most inner three depth levels and the closing brackets are
always on the same indentation as the openeing of the object instead
of at the same line as another property.

Big strings will be naturally broken into multiple lines instead of
having one huge line that is not well readable.

The output size mainly stays the same that way while it will be
smaller in case of big arrays.

Increasing the `breakLength` to 80 adjusts for most terminals that
support at least 80 characters in a single line and improves the
general output that way. A lot of calculations use the `breakLength`
to determine the concrete behavior.

PR-URL: https://github.com/nodejs/node/pull/27109
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Minwoo Jung <minwoo@nodesource.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
Ruben Bridgewater 2019-04-05 22:18:16 +02:00
parent 892c51f330
commit c9fece38c8
No known key found for this signature in database
GPG Key ID: F07496B3EB3C1762
13 changed files with 198 additions and 162 deletions

View File

@ -390,6 +390,10 @@ stream.write('With ES6');
<!-- YAML <!-- YAML
added: v0.3.0 added: v0.3.0
changes: changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/27109
description: The `compact` options default is changed to `3` and the
`breakLength` options default is changed to `80`.
- version: v11.11.0 - version: v11.11.0
pr-url: https://github.com/nodejs/node/pull/26269 pr-url: https://github.com/nodejs/node/pull/26269
description: The `compact` option accepts numbers for a new output mode. description: The `compact` option accepts numbers for a new output mode.
@ -463,16 +467,17 @@ changes:
[`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when
formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or
negative to show no elements. **Default:** `100`. negative to show no elements. **Default:** `100`.
* `breakLength` {integer} The length at which an object's keys are split * `breakLength` {integer} The length at which input values are split across
across multiple lines. Set to `Infinity` to format an object as a single multiple lines. Set to `Infinity` to format the input as a single line
line. **Default:** `60` for legacy compatibility. (in combination with `compact` set to `true` or any number >= `1`).
**Default:** `80`.
* `compact` {boolean|integer} Setting this to `false` causes each object key * `compact` {boolean|integer} Setting this to `false` causes each object key
to be displayed on a new line. It will also add new lines to text that is to be displayed on a new line. It will also add new lines to text that is
longer than `breakLength`. If set to a number, the most `n` inner elements longer than `breakLength`. If set to a number, the most `n` inner elements
are united on a single line as long as all properties fit into are united on a single line as long as all properties fit into
`breakLength`. Short array elements are also grouped together. Note that no `breakLength`. Short array elements are also grouped together. Note that no
text will be reduced below 16 characters, no matter the `breakLength` size. text will be reduced below 16 characters, no matter the `breakLength` size.
For more information, see the example below. **Default:** `true`. For more information, see the example below. **Default:** `3`.
* `sorted` {boolean|Function} If set to `true` or a function, all properties * `sorted` {boolean|Function} If set to `true` or a function, all properties
of an object, and `Set` and `Map` entries are sorted in the resulting of an object, and `Set` and `Map` entries are sorted in the resulting
string. If set to `true` the [default sort][] is used. If set to a function, string. If set to `true` the [default sort][] is used. If set to a function,

View File

@ -95,8 +95,8 @@ const inspectDefaultOptions = Object.seal({
customInspect: true, customInspect: true,
showProxy: false, showProxy: false,
maxArrayLength: 100, maxArrayLength: 100,
breakLength: 60, breakLength: 80,
compact: true, compact: 3,
sorted: false, sorted: false,
getters: false getters: false
}); });

View File

@ -122,11 +122,13 @@ function teardown() {
const expectedOut = 'not indented\n' + const expectedOut = 'not indented\n' +
' indented\n' + ' indented\n' +
' also indented\n' + ' also indented\n' +
" { also: 'a',\n" + ' {\n' +
" also: 'a',\n" +
" multiline: 'object',\n" + " multiline: 'object',\n" +
" should: 'be',\n" + " should: 'be',\n" +
" indented: 'properly',\n" + " indented: 'properly',\n" +
" kthx: 'bai' }\n"; " kthx: 'bai'\n" +
' }\n';
const expectedErr = ''; const expectedErr = '';
c.log('not indented'); c.log('not indented');

View File

@ -234,11 +234,11 @@ for (const expected of expectedStrings) {
} }
assert.strictEqual(strings.shift(), assert.strictEqual(strings.shift(),
"{ foo: 'bar',\n [Symbol(nodejs.util.inspect.custom)]: " + "{\n foo: 'bar',\n [Symbol(nodejs.util.inspect.custom)]:" +
'[Function: [nodejs.util.inspect.custom]] }\n'); ' [Function: [nodejs.util.inspect.custom]]\n}\n');
assert.strictEqual(strings.shift(), assert.strictEqual(strings.shift(),
"{ foo: 'bar',\n [Symbol(nodejs.util.inspect.custom)]: " + "{\n foo: 'bar',\n [Symbol(nodejs.util.inspect.custom)]:" +
'[Function: [nodejs.util.inspect.custom]] }\n'); ' [Function: [nodejs.util.inspect.custom]]\n}\n');
assert.ok(strings.shift().includes('foo: [Object]')); assert.ok(strings.shift().includes('foo: [Object]'));
assert.strictEqual(strings.shift().includes('baz'), false); assert.strictEqual(strings.shift().includes('baz'), false);
assert.strictEqual(strings.shift(), 'inspect inspect\n'); assert.strictEqual(strings.shift(), 'inspect inspect\n');

View File

@ -11,7 +11,7 @@ const server = http2.createServer();
server.on('stream', common.mustCall((stream) => { server.on('stream', common.mustCall((stream) => {
assert.strictEqual(stream.aborted, false); assert.strictEqual(stream.aborted, false);
const insp = util.inspect(stream); const insp = util.inspect(stream);
assert.ok(/Http2Stream { id/.test(insp)); assert.ok(/Http2Stream {/.test(insp));
assert.ok(/ state:/.test(insp)); assert.ok(/ state:/.test(insp));
assert.ok(/ readableState:/.test(insp)); assert.ok(/ readableState:/.test(insp));
assert.ok(/ writableState:/.test(insp)); assert.ok(/ writableState:/.test(insp));

View File

@ -30,7 +30,7 @@ function run({ command, expected, ...extraREPLOptions }) {
const tests = [ const tests = [
{ {
// test .load for a file that throws // Test .load for a file that throws.
command: `.load ${fixtures.path('repl-pretty-stack.js')}`, command: `.load ${fixtures.path('repl-pretty-stack.js')}`,
expected: 'Thrown:\nError: Whoops!\n at repl:9:24\n' + expected: 'Thrown:\nError: Whoops!\n at repl:9:24\n' +
' at d (repl:12:3)\n at c (repl:9:3)\n' + ' at d (repl:12:3)\n at c (repl:9:3)\n' +
@ -48,20 +48,20 @@ const tests = [
{ {
command: '(() => { const err = Error(\'Whoops!\'); ' + command: '(() => { const err = Error(\'Whoops!\'); ' +
'err.foo = \'bar\'; throw err; })()', 'err.foo = \'bar\'; throw err; })()',
expected: 'Thrown:\n{ Error: Whoops!\n at repl:1:22\n foo: \'bar\' }\n', expected: "Thrown:\nError: Whoops!\n at repl:1:22 {\n foo: 'bar'\n}\n",
}, },
{ {
command: '(() => { const err = Error(\'Whoops!\'); ' + command: '(() => { const err = Error(\'Whoops!\'); ' +
'err.foo = \'bar\'; throw err; })()', 'err.foo = \'bar\'; throw err; })()',
expected: 'Thrown:\n{ Error: Whoops!\n at repl:1:22\n foo: ' + expected: 'Thrown:\nError: Whoops!\n at repl:1:22 {\n foo: ' +
"\u001b[32m'bar'\u001b[39m }\n", "\u001b[32m'bar'\u001b[39m\n}\n",
useColors: true useColors: true
}, },
{ {
command: 'foo = bar;', command: 'foo = bar;',
expected: 'Thrown:\nReferenceError: bar is not defined\n' expected: 'Thrown:\nReferenceError: bar is not defined\n'
}, },
// test anonymous IIFE // Test anonymous IIFE.
{ {
command: '(function() { throw new Error(\'Whoops!\'); })()', command: '(function() { throw new Error(\'Whoops!\'); })()',
expected: 'Thrown:\nError: Whoops!\n at repl:1:21\n' expected: 'Thrown:\nError: Whoops!\n at repl:1:21\n'

View File

@ -179,12 +179,13 @@ function testError() {
// The sync error, with individual property echoes // The sync error, with individual property echoes
'Thrown:', 'Thrown:',
/^{ Error: ENOENT: no such file or directory, scandir '.*nonexistent.*'/, /^Error: ENOENT: no such file or directory, scandir '.*nonexistent\?'/,
/Object\.readdirSync/, /Object\.readdirSync/,
/^ errno: -(2|4058),$/, /^ errno: -(2|4058),$/,
" syscall: 'scandir',", " syscall: 'scandir',",
" code: 'ENOENT',", " code: 'ENOENT',",
" path: '/nonexistent?' }", " path: '/nonexistent?'",
'}',
"'ENOENT'", "'ENOENT'",
"'scandir'", "'scandir'",

View File

@ -534,7 +534,7 @@ const errorTests = [
send: 'require("internal/repl")', send: 'require("internal/repl")',
expect: [ expect: [
'Thrown:', 'Thrown:',
/^{ Error: Cannot find module 'internal\/repl'/, /^Error: Cannot find module 'internal\/repl'/,
/^Require stack:/, /^Require stack:/,
/^- <repl>/, /^- <repl>/,
/^ at .*/, /^ at .*/,
@ -542,7 +542,8 @@ const errorTests = [
/^ at .*/, /^ at .*/,
/^ at .*/, /^ at .*/,
" code: 'MODULE_NOT_FOUND',", " code: 'MODULE_NOT_FOUND',",
" requireStack: [ '<repl>' ] }" " requireStack: [ '<repl>' ]",
'}'
] ]
}, },
// REPL should handle quotes within regexp literal in multiline mode // REPL should handle quotes within regexp literal in multiline mode

View File

@ -165,59 +165,74 @@ assert.strictEqual(util.format('%o', 42), '42');
assert.strictEqual(util.format('%o', 'foo'), '\'foo\''); assert.strictEqual(util.format('%o', 'foo'), '\'foo\'');
assert.strictEqual( assert.strictEqual(
util.format('%o', obj), util.format('%o', obj),
'{ foo: \'bar\',\n' + '{\n' +
' foo: \'bar\',\n' +
' foobar: 1,\n' + ' foobar: 1,\n' +
' func:\n' + ' func: [Function: func] {\n' +
' { [Function: func]\n' + ' [length]: 0,\n' +
' [length]: 0,\n' + ' [name]: \'func\',\n' +
' [name]: \'func\',\n' + ' [prototype]: func { [constructor]: [Circular] }\n' +
' [prototype]: func { [constructor]: [Circular] } } }'); ' }\n' +
'}');
assert.strictEqual( assert.strictEqual(
util.format('%o', nestedObj2), util.format('%o', nestedObj2),
'{ foo: \'bar\',\n' + '{\n' +
' foo: \'bar\',\n' +
' foobar: 1,\n' + ' foobar: 1,\n' +
' func:\n' + ' func: [\n' +
' [ { a:\n' + ' {\n' +
' { [Function: a]\n' + ' a: [Function: a] {\n' +
' [length]: 0,\n' + ' [length]: 0,\n' +
' [name]: \'a\',\n' + ' [name]: \'a\',\n' +
' [prototype]: a { [constructor]: [Circular] } } },\n' + ' [prototype]: a { [constructor]: [Circular] }\n' +
' [length]: 1 ] }'); ' }\n' +
' },\n' +
' [length]: 1\n' +
' ]\n' +
'}');
assert.strictEqual( assert.strictEqual(
util.format('%o', nestedObj), util.format('%o', nestedObj),
'{ foo: \'bar\',\n' + '{\n' +
' foobar:\n' + ' foo: \'bar\',\n' +
' { foo: \'bar\',\n' + ' foobar: {\n' +
' func:\n' + ' foo: \'bar\',\n' +
' { [Function: func]\n' + ' func: [Function: func] {\n' +
' [length]: 0,\n' + ' [length]: 0,\n' +
' [name]: \'func\',\n' + ' [name]: \'func\',\n' +
' [prototype]: func { [constructor]: [Circular] } } } }'); ' [prototype]: func { [constructor]: [Circular] }\n' +
' }\n' +
' }\n' +
'}');
assert.strictEqual( assert.strictEqual(
util.format('%o %o', obj, obj), util.format('%o %o', obj, obj),
'{ foo: \'bar\',\n' + '{\n' +
' foo: \'bar\',\n' +
' foobar: 1,\n' + ' foobar: 1,\n' +
' func:\n' + ' func: [Function: func] {\n' +
' { [Function: func]\n' + ' [length]: 0,\n' +
' [length]: 0,\n' + ' [name]: \'func\',\n' +
' [name]: \'func\',\n' + ' [prototype]: func { [constructor]: [Circular] }\n' +
' [prototype]: func { [constructor]: [Circular] } } }' + ' }\n' +
' { foo: \'bar\',\n' + '} {\n' +
' foo: \'bar\',\n' +
' foobar: 1,\n' + ' foobar: 1,\n' +
' func:\n' + ' func: [Function: func] {\n' +
' { [Function: func]\n' + ' [length]: 0,\n' +
' [length]: 0,\n' + ' [name]: \'func\',\n' +
' [name]: \'func\',\n' + ' [prototype]: func { [constructor]: [Circular] }\n' +
' [prototype]: func { [constructor]: [Circular] } } }'); ' }\n' +
'}');
assert.strictEqual( assert.strictEqual(
util.format('%o %o', obj), util.format('%o %o', obj),
'{ foo: \'bar\',\n' + '{\n' +
' foo: \'bar\',\n' +
' foobar: 1,\n' + ' foobar: 1,\n' +
' func:\n' + ' func: [Function: func] {\n' +
' { [Function: func]\n' + ' [length]: 0,\n' +
' [length]: 0,\n' + ' [name]: \'func\',\n' +
' [name]: \'func\',\n' + ' [prototype]: func { [constructor]: [Circular] }\n' +
' [prototype]: func { [constructor]: [Circular] } } } %o'); ' }\n' +
'} %o');
assert.strictEqual(util.format('%O'), '%O'); assert.strictEqual(util.format('%O'), '%O');
assert.strictEqual(util.format('%O', 42), '42'); assert.strictEqual(util.format('%O', 42), '42');

View File

@ -51,7 +51,8 @@ assert.strictEqual(
util.inspect(proxyObj, opts), util.inspect(proxyObj, opts),
'Proxy [\n' + 'Proxy [\n' +
' [ 1, 2, 3 ],\n' + ' [ 1, 2, 3 ],\n' +
' { getPrototypeOf: [Function: getPrototypeOf],\n' + ' {\n' +
' getPrototypeOf: [Function: getPrototypeOf],\n' +
' setPrototypeOf: [Function: setPrototypeOf],\n' + ' setPrototypeOf: [Function: setPrototypeOf],\n' +
' isExtensible: [Function: isExtensible],\n' + ' isExtensible: [Function: isExtensible],\n' +
' preventExtensions: [Function: preventExtensions],\n' + ' preventExtensions: [Function: preventExtensions],\n' +
@ -63,7 +64,9 @@ assert.strictEqual(
' deleteProperty: [Function: deleteProperty],\n' + ' deleteProperty: [Function: deleteProperty],\n' +
' ownKeys: [Function: ownKeys],\n' + ' ownKeys: [Function: ownKeys],\n' +
' apply: [Function: apply],\n' + ' apply: [Function: apply],\n' +
' construct: [Function: construct] } ]' ' construct: [Function: construct]\n' +
' }\n' +
']'
); );
// Using getProxyDetails with non-proxy returns undefined // Using getProxyDetails with non-proxy returns undefined
@ -89,14 +92,18 @@ const expected3 = 'Proxy [ Proxy [ Proxy [ {}, {} ], {} ], Proxy [ {}, {} ] ]';
const expected4 = 'Proxy [ Proxy [ {}, {} ], Proxy [ Proxy [ {}, {} ], {} ] ]'; const expected4 = 'Proxy [ Proxy [ {}, {} ], Proxy [ Proxy [ {}, {} ], {} ] ]';
const expected5 = 'Proxy [\n ' + const expected5 = 'Proxy [\n ' +
'Proxy [ Proxy [ Proxy [Array], {} ], Proxy [ {}, {} ] ],\n' + 'Proxy [ Proxy [ Proxy [Array], {} ], Proxy [ {}, {} ] ],\n' +
' Proxy [ Proxy [ {}, {} ], Proxy [ Proxy [Array], {} ] ] ]'; ' Proxy [ Proxy [ {}, {} ], Proxy [ Proxy [Array], {} ] ]' +
'\n]';
const expected6 = 'Proxy [\n' + const expected6 = 'Proxy [\n' +
' Proxy [\n' + ' Proxy [\n' +
' Proxy [ Proxy [Array], Proxy [Array] ],\n' + ' Proxy [ Proxy [Array], Proxy [Array] ],\n' +
' Proxy [ Proxy [Array], Proxy [Array] ] ],\n' + ' Proxy [ Proxy [Array], Proxy [Array] ]\n' +
' ],\n' +
' Proxy [\n' + ' Proxy [\n' +
' Proxy [ Proxy [Array], Proxy [Array] ],\n' + ' Proxy [ Proxy [Array], Proxy [Array] ],\n' +
' Proxy [ Proxy [Array], Proxy [Array] ] ] ]'; ' Proxy [ Proxy [Array], Proxy [Array] ]\n' +
' ]\n' +
']';
assert.strictEqual( assert.strictEqual(
util.inspect(proxy1, { showProxy: true, depth: null }), util.inspect(proxy1, { showProxy: true, depth: null }),
expected1); expected1);

View File

@ -49,7 +49,7 @@ assert.strictEqual(util.inspect(new Date('')), (new Date('')).toString());
assert.strictEqual(util.inspect('\n\u0001'), "'\\n\\u0001'"); assert.strictEqual(util.inspect('\n\u0001'), "'\\n\\u0001'");
assert.strictEqual( assert.strictEqual(
util.inspect(`${Array(75).fill(1)}'\n\u001d\n\u0003`), util.inspect(`${Array(75).fill(1)}'\n\u001d\n\u0003`),
`"${Array(75).fill(1)}'\\n\\u001d\\n\\u0003"` `"${Array(75).fill(1)}'\\n" +\n '\\u001d\\n\\u0003'`
); );
assert.strictEqual(util.inspect([]), '[]'); assert.strictEqual(util.inspect([]), '[]');
assert.strictEqual(util.inspect(Object.create([])), 'Array {}'); assert.strictEqual(util.inspect(Object.create([])), 'Array {}');
@ -72,7 +72,7 @@ assert.strictEqual(util.inspect({ 'a': { 'b': { 'c': { 'd': 2 } } } }),
'{ a: { b: { c: [Object] } } }'); '{ a: { b: { c: [Object] } } }');
assert.strictEqual( assert.strictEqual(
util.inspect({ 'a': { 'b': { 'c': { 'd': 2 } } } }, false, null), util.inspect({ 'a': { 'b': { 'c': { 'd': 2 } } } }, false, null),
'{ a: { b: { c: { d: 2 } } } }'); '{\n a: { b: { c: { d: 2 } } }\n}');
assert.strictEqual(util.inspect([1, 2, 3], true), '[ 1, 2, 3, [length]: 3 ]'); assert.strictEqual(util.inspect([1, 2, 3], true), '[ 1, 2, 3, [length]: 3 ]');
assert.strictEqual(util.inspect({ 'a': { 'b': { 'c': 2 } } }, false, 0), assert.strictEqual(util.inspect({ 'a': { 'b': { 'c': 2 } } }, false, 0),
'{ a: [Object] }'); '{ a: [Object] }');
@ -96,7 +96,7 @@ assert.strictEqual(
Object.assign(new String('hello'), { [Symbol('foo')]: 123 }), Object.assign(new String('hello'), { [Symbol('foo')]: 123 }),
{ showHidden: true } { showHidden: true }
), ),
"{ [String: 'hello'] [length]: 5, [Symbol(foo)]: 123 }" "[String: 'hello'] { [length]: 5, [Symbol(foo)]: 123 }"
); );
assert.strictEqual(util.inspect((new JSStream())._externalStream), assert.strictEqual(util.inspect((new JSStream())._externalStream),
@ -127,9 +127,8 @@ assert(!/Object/.test(
'DataView {\n' + 'DataView {\n' +
' byteLength: 2,\n' + ' byteLength: 2,\n' +
' byteOffset: 1,\n' + ' byteOffset: 1,\n' +
' buffer:\n' + ' buffer: ArrayBuffer {' +
' ArrayBuffer { [Uint8Contents]: ' + ' [Uint8Contents]: <01 02 03 04>, byteLength: 4 }\n}');
'<01 02 03 04>, byteLength: 4 } }');
assert.strictEqual( assert.strictEqual(
util.inspect(ab, showHidden), util.inspect(ab, showHidden),
'ArrayBuffer { [Uint8Contents]: <01 02 03 04>, byteLength: 4 }' 'ArrayBuffer { [Uint8Contents]: <01 02 03 04>, byteLength: 4 }'
@ -138,9 +137,8 @@ assert(!/Object/.test(
'DataView {\n' + 'DataView {\n' +
' byteLength: 2,\n' + ' byteLength: 2,\n' +
' byteOffset: 1,\n' + ' byteOffset: 1,\n' +
' buffer:\n' + ' buffer: ArrayBuffer { [Uint8Contents]: ' +
' ArrayBuffer { [Uint8Contents]: ' + '<01 02 03 04>, byteLength: 4 }\n}');
'<01 02 03 04>, byteLength: 4 } }');
ab.x = 42; ab.x = 42;
dv.y = 1337; dv.y = 1337;
assert.strictEqual(util.inspect(ab, showHidden), assert.strictEqual(util.inspect(ab, showHidden),
@ -150,10 +148,9 @@ assert(!/Object/.test(
'DataView {\n' + 'DataView {\n' +
' byteLength: 2,\n' + ' byteLength: 2,\n' +
' byteOffset: 1,\n' + ' byteOffset: 1,\n' +
' buffer:\n' + ' buffer: ArrayBuffer { [Uint8Contents]: <01 02 03 04>,' +
' ArrayBuffer { [Uint8Contents]: <01 02 03 04>, ' + ' byteLength: 4, x: 42 },\n' +
'byteLength: 4, x: 42 },\n' + ' y: 1337\n}');
' y: 1337 }');
} }
// Now do the same checks but from a different context. // Now do the same checks but from a different context.
@ -169,9 +166,8 @@ assert(!/Object/.test(
'DataView {\n' + 'DataView {\n' +
' byteLength: 2,\n' + ' byteLength: 2,\n' +
' byteOffset: 1,\n' + ' byteOffset: 1,\n' +
' buffer:\n' + ' buffer: ArrayBuffer { [Uint8Contents]: <00 00 00 00>,' +
' ArrayBuffer { [Uint8Contents]: <00 00 00 00>, ' + ' byteLength: 4 }\n}');
'byteLength: 4 } }');
assert.strictEqual( assert.strictEqual(
util.inspect(ab, showHidden), util.inspect(ab, showHidden),
'ArrayBuffer { [Uint8Contents]: <00 00 00 00>, byteLength: 4 }' 'ArrayBuffer { [Uint8Contents]: <00 00 00 00>, byteLength: 4 }'
@ -180,9 +176,8 @@ assert(!/Object/.test(
'DataView {\n' + 'DataView {\n' +
' byteLength: 2,\n' + ' byteLength: 2,\n' +
' byteOffset: 1,\n' + ' byteOffset: 1,\n' +
' buffer:\n' + ' buffer: ArrayBuffer { [Uint8Contents]: <00 00 00 00>,' +
' ArrayBuffer { [Uint8Contents]: <00 00 00 00>, ' + ' byteLength: 4 }\n}');
'byteLength: 4 } }');
ab.x = 42; ab.x = 42;
dv.y = 1337; dv.y = 1337;
assert.strictEqual(util.inspect(ab, showHidden), assert.strictEqual(util.inspect(ab, showHidden),
@ -192,10 +187,9 @@ assert(!/Object/.test(
'DataView {\n' + 'DataView {\n' +
' byteLength: 2,\n' + ' byteLength: 2,\n' +
' byteOffset: 1,\n' + ' byteOffset: 1,\n' +
' buffer:\n' + ' buffer: ArrayBuffer { [Uint8Contents]: <00 00 00 00>,' +
' ArrayBuffer { [Uint8Contents]: <00 00 00 00>,' +
' byteLength: 4, x: 42 },\n' + ' byteLength: 4, x: 42 },\n' +
' y: 1337 }'); ' y: 1337\n}');
} }
[ Float32Array, [ Float32Array,
@ -221,7 +215,7 @@ assert(!/Object/.test(
` [length]: ${length},\n` + ` [length]: ${length},\n` +
` [byteLength]: ${byteLength},\n` + ` [byteLength]: ${byteLength},\n` +
' [byteOffset]: 0,\n' + ' [byteOffset]: 0,\n' +
` [buffer]: ArrayBuffer { byteLength: ${byteLength} } ]`); ` [buffer]: ArrayBuffer { byteLength: ${byteLength} }\n]`);
assert.strictEqual( assert.strictEqual(
util.inspect(array, false), util.inspect(array, false),
`${constructor.name} [ 65, 97 ]` `${constructor.name} [ 65, 97 ]`
@ -255,7 +249,7 @@ assert(!/Object/.test(
` [length]: ${length},\n` + ` [length]: ${length},\n` +
` [byteLength]: ${byteLength},\n` + ` [byteLength]: ${byteLength},\n` +
' [byteOffset]: 0,\n' + ' [byteOffset]: 0,\n' +
` [buffer]: ArrayBuffer { byteLength: ${byteLength} } ]`); ` [buffer]: ArrayBuffer { byteLength: ${byteLength} }\n]`);
assert.strictEqual( assert.strictEqual(
util.inspect(array, false), util.inspect(array, false),
`${constructor.name} [ 65, 97 ]` `${constructor.name} [ 65, 97 ]`
@ -397,11 +391,12 @@ assert.strictEqual(
delete arr[0]; delete arr[0];
delete arr[10]; delete arr[10];
assert.strictEqual(util.inspect(arr), assert.strictEqual(util.inspect(arr),
['[ <4294967294 empty items>,', ['[',
'<4294967294 empty items>,',
'true,', 'true,',
"'4294967296': true,", "'4294967296': true,",
"'4294967295': true,", "'4294967295': true,",
"'4294967297': true ]" "'4294967297': true\n]"
].join('\n ')); ].join('\n '));
} }
@ -409,21 +404,21 @@ assert.strictEqual(
{ {
const value = () => {}; const value = () => {};
value.aprop = 42; value.aprop = 42;
assert.strictEqual(util.inspect(value), '{ [Function: value] aprop: 42 }'); assert.strictEqual(util.inspect(value), '[Function: value] { aprop: 42 }');
} }
// Anonymous function with properties. // Anonymous function with properties.
{ {
const value = (() => function() {})(); const value = (() => function() {})();
value.aprop = 42; value.aprop = 42;
assert.strictEqual(util.inspect(value), '{ [Function] aprop: 42 }'); assert.strictEqual(util.inspect(value), '[Function] { aprop: 42 }');
} }
// Regular expressions with properties. // Regular expressions with properties.
{ {
const value = /123/ig; const value = /123/ig;
value.aprop = 42; value.aprop = 42;
assert.strictEqual(util.inspect(value), '{ /123/gi aprop: 42 }'); assert.strictEqual(util.inspect(value), '/123/gi { aprop: 42 }');
} }
// Dates with properties. // Dates with properties.
@ -431,7 +426,7 @@ assert.strictEqual(
const value = new Date('Sun, 14 Feb 2010 11:48:40 GMT'); const value = new Date('Sun, 14 Feb 2010 11:48:40 GMT');
value.aprop = 42; value.aprop = 42;
assert.strictEqual(util.inspect(value), assert.strictEqual(util.inspect(value),
'{ 2010-02-14T11:48:40.000Z aprop: 42 }'); '2010-02-14T11:48:40.000Z { aprop: 42 }');
} }
// Test the internal isDate implementation. // Test the internal isDate implementation.
@ -649,7 +644,7 @@ assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}');
{ {
const x = { [util.inspect.custom]: util.inspect }; const x = { [util.inspect.custom]: util.inspect };
assert(util.inspect(x).includes( assert(util.inspect(x).includes(
'[Symbol(nodejs.util.inspect.custom)]:\n { [Function: inspect]')); '[Symbol(nodejs.util.inspect.custom)]: [Function: inspect] {\n'));
} }
// `util.inspect` should display the escaped value of a key. // `util.inspect` should display the escaped value of a key.
@ -814,8 +809,10 @@ util.inspect({ hasOwnProperty: null });
// Returning `this` from a custom inspection function works. // Returning `this` from a custom inspection function works.
const subject = { a: 123, [util.inspect.custom]() { return this; } }; const subject = { a: 123, [util.inspect.custom]() { return this; } };
const UIC = 'nodejs.util.inspect.custom'; const UIC = 'nodejs.util.inspect.custom';
assert.strictEqual(util.inspect(subject), assert.strictEqual(
`{ a: 123,\n [Symbol(${UIC})]: [Function: [${UIC}]] }`); util.inspect(subject),
`{\n a: 123,\n [Symbol(${UIC})]: [Function: [${UIC}]]\n}`
);
} }
// Verify that it's possible to use the stylize function to manipulate input. // Verify that it's possible to use the stylize function to manipulate input.
@ -866,23 +863,23 @@ assert.strictEqual(util.inspect(new Number(13.37)), '[Number: 13.37]');
{ {
const str = new String('baz'); const str = new String('baz');
str.foo = 'bar'; str.foo = 'bar';
assert.strictEqual(util.inspect(str), "{ [String: 'baz'] foo: 'bar' }"); assert.strictEqual(util.inspect(str), "[String: 'baz'] { foo: 'bar' }");
const bool = new Boolean(true); const bool = new Boolean(true);
bool.foo = 'bar'; bool.foo = 'bar';
assert.strictEqual(util.inspect(bool), "{ [Boolean: true] foo: 'bar' }"); assert.strictEqual(util.inspect(bool), "[Boolean: true] { foo: 'bar' }");
const num = new Number(13.37); const num = new Number(13.37);
num.foo = 'bar'; num.foo = 'bar';
assert.strictEqual(util.inspect(num), "{ [Number: 13.37] foo: 'bar' }"); assert.strictEqual(util.inspect(num), "[Number: 13.37] { foo: 'bar' }");
const sym = Object(Symbol('foo')); const sym = Object(Symbol('foo'));
sym.foo = 'bar'; sym.foo = 'bar';
assert.strictEqual(util.inspect(sym), "{ [Symbol: Symbol(foo)] foo: 'bar' }"); assert.strictEqual(util.inspect(sym), "[Symbol: Symbol(foo)] { foo: 'bar' }");
const big = Object(BigInt(55)); const big = Object(BigInt(55));
big.foo = 'bar'; big.foo = 'bar';
assert.strictEqual(util.inspect(big), "{ [BigInt: 55n] foo: 'bar' }"); assert.strictEqual(util.inspect(big), "[BigInt: 55n] { foo: 'bar' }");
} }
// Test es6 Symbol. // Test es6 Symbol.
@ -1041,17 +1038,18 @@ if (typeof Symbol !== 'undefined') {
// Test alignment of items in container. // Test alignment of items in container.
// Assumes that the first numeric character is the start of an item. // Assumes that the first numeric character is the start of an item.
{ {
function checkAlignment(container) { function checkAlignment(container, start, lineX, end) {
const lines = util.inspect(container).split('\n'); const lines = util.inspect(container).split('\n');
const numRE = /\d/; lines.forEach((line, i) => {
let pos; if (i === 0) {
lines.forEach((line) => { assert.strictEqual(line, start);
const npos = line.search(numRE); } else if (i === lines.length - 1) {
if (npos !== -1) { assert.strictEqual(line, end);
if (pos !== undefined) { } else {
assert.strictEqual(pos, npos); let expected = lineX.replace('X', i - 1);
} if (i !== lines.length - 2)
pos = npos; expected += ',';
assert.strictEqual(line, expected);
} }
}); });
} }
@ -1066,10 +1064,12 @@ if (typeof Symbol !== 'undefined') {
obj[prop] = null; obj[prop] = null;
}); });
checkAlignment(bigArray); checkAlignment(obj, '{', " 'X': null", '}');
checkAlignment(obj); checkAlignment(new Set(bigArray), 'Set {', ' X', '}');
checkAlignment(new Set(bigArray)); checkAlignment(
checkAlignment(new Map(bigArray.map((number) => [number, null]))); new Map(bigArray.map((number) => [number, null])),
'Map {', ' X => null', '}'
);
} }
@ -1151,8 +1151,8 @@ if (typeof Symbol !== 'undefined') {
// https://github.com/nodejs/node/pull/6334 is backported. // https://github.com/nodejs/node/pull/6334 is backported.
{ {
const x = new Array(101).fill(); const x = new Array(101).fill();
assert(util.inspect(x).endsWith('1 more item ]')); assert(util.inspect(x).endsWith('1 more item\n]'));
assert(!util.inspect(x, { maxArrayLength: 101 }).endsWith('1 more item ]')); assert(!util.inspect(x, { maxArrayLength: 101 }).endsWith('1 more item\n]'));
assert.strictEqual( assert.strictEqual(
util.inspect(x, { maxArrayLength: -1 }), util.inspect(x, { maxArrayLength: -1 }),
'[ ... 101 more items ]' '[ ... 101 more items ]'
@ -1165,7 +1165,7 @@ if (typeof Symbol !== 'undefined') {
const x = Array(101); const x = Array(101);
assert.strictEqual(util.inspect(x, { maxArrayLength: 0 }), assert.strictEqual(util.inspect(x, { maxArrayLength: 0 }),
'[ ... 101 more items ]'); '[ ... 101 more items ]');
assert(!util.inspect(x, { maxArrayLength: null }).endsWith('1 more item ]')); assert(!util.inspect(x, { maxArrayLength: null }).endsWith('1 more item\n]'));
assert(!util.inspect( assert(!util.inspect(
x, { maxArrayLength: Infinity } x, { maxArrayLength: Infinity }
).endsWith('1 more item ]')); ).endsWith('1 more item ]'));
@ -1173,12 +1173,12 @@ if (typeof Symbol !== 'undefined') {
{ {
const x = new Uint8Array(101); const x = new Uint8Array(101);
assert(util.inspect(x).endsWith('1 more item ]')); assert(util.inspect(x).endsWith('1 more item\n]'));
assert(!util.inspect(x, { maxArrayLength: 101 }).endsWith('1 more item ]')); assert(!util.inspect(x, { maxArrayLength: 101 }).endsWith('1 more item\n]'));
assert.strictEqual(util.inspect(x, { maxArrayLength: 0 }), assert.strictEqual(util.inspect(x, { maxArrayLength: 0 }),
'Uint8Array [ ... 101 more items ]'); 'Uint8Array [ ... 101 more items ]');
assert(!util.inspect(x, { maxArrayLength: null }).endsWith('1 more item ]')); assert(!util.inspect(x, { maxArrayLength: null }).endsWith('1 more item\n]'));
assert(util.inspect(x, { maxArrayLength: Infinity }).endsWith(' 0 ]')); assert(util.inspect(x, { maxArrayLength: Infinity }).endsWith(' 0, 0\n]'));
} }
{ {
@ -1190,9 +1190,11 @@ if (typeof Symbol !== 'undefined') {
const twoLines = util.inspect(obj, { breakLength: breakpoint }); const twoLines = util.inspect(obj, { breakLength: breakpoint });
assert.strictEqual(oneLine, "{ foo: 'abc', bar: 'xyz' }"); assert.strictEqual(oneLine, "{ foo: 'abc', bar: 'xyz' }");
assert.strictEqual(oneLine, assert.strictEqual(
util.inspect(obj, { breakLength: breakpoint + 1 })); util.inspect(obj, { breakLength: breakpoint + 1 }),
assert.strictEqual(twoLines, "{ foo: 'abc',\n bar: 'xyz' }"); twoLines
);
assert.strictEqual(twoLines, "{\n foo: 'abc',\n bar: 'xyz'\n}");
} }
// util.inspect.defaultOptions tests. // util.inspect.defaultOptions tests.
@ -1545,7 +1547,9 @@ util.inspect(process);
assert.strict.equal(out, expected); assert.strict.equal(out, expected);
out = util.inspect(map, { showHidden: true, depth: 9, breakLength: 4 }); out = util.inspect(map, {
showHidden: true, depth: 9, breakLength: 4, compact: true
});
expected = [ expected = [
'Map {', 'Map {',
' Promise {', ' Promise {',
@ -1712,18 +1716,18 @@ assert.strictEqual(util.inspect('"\'${a}'), "'\"\\'${a}'");
delete foo[Symbol.toStringTag]; delete foo[Symbol.toStringTag];
assert( assert(
util.inspect(foo).startsWith( util.inspect(foo).startsWith(
`{ [${name}: null prototype]${message ? `: ${message}` : '\n'}`), `[${name}: null prototype]${message ? `: ${message}` : '\n'}`),
util.inspect(foo) util.inspect(foo)
); );
foo.stack = 'This is a stack'; foo.stack = 'This is a stack';
assert.strictEqual( assert.strictEqual(
util.inspect(foo), util.inspect(foo),
'{ [[Error: null prototype]: This is a stack] bar: true }' '[[Error: null prototype]: This is a stack] { bar: true }'
); );
foo.stack = stack.split('\n')[0]; foo.stack = stack.split('\n')[0];
assert.strictEqual( assert.strictEqual(
util.inspect(foo), util.inspect(foo),
`{ [[${name}: null prototype]${message ? `: ${message}` : ''}] bar: true }` `[[${name}: null prototype]${message ? `: ${message}` : ''}] { bar: true }`
); );
}); });
@ -1789,12 +1793,12 @@ assert.strictEqual(util.inspect('"\'${a}'), "'\"\\'${a}'");
[new BigUint64Array(2), '[BigUint64Array: null prototype] [ 0n, 0n ]'], [new BigUint64Array(2), '[BigUint64Array: null prototype] [ 0n, 0n ]'],
[new ArrayBuffer(16), '[ArrayBuffer: null prototype] {\n' + [new ArrayBuffer(16), '[ArrayBuffer: null prototype] {\n' +
' [Uint8Contents]: <00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00>,\n' + ' [Uint8Contents]: <00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00>,\n' +
' byteLength: undefined }'], ' byteLength: undefined\n}'],
[new DataView(new ArrayBuffer(16)), [new DataView(new ArrayBuffer(16)),
'[DataView: null prototype] {\n byteLength: undefined,\n ' + '[DataView: null prototype] {\n byteLength: undefined,\n ' +
'byteOffset: undefined,\n buffer: undefined }'], 'byteOffset: undefined,\n buffer: undefined\n}'],
[new SharedArrayBuffer(2), '[SharedArrayBuffer: null prototype] ' + [new SharedArrayBuffer(2), '[SharedArrayBuffer: null prototype] ' +
'{ [Uint8Contents]: <00 00>, byteLength: undefined }'], '{\n [Uint8Contents]: <00 00>,\n byteLength: undefined\n}'],
[/foobar/, '[RegExp: null prototype] /foobar/'], [/foobar/, '[RegExp: null prototype] /foobar/'],
[new Date('Sun, 14 Feb 2010 11:48:40 GMT'), [new Date('Sun, 14 Feb 2010 11:48:40 GMT'),
'[Date: null prototype] 2010-02-14T11:48:40.000Z'] '[Date: null prototype] 2010-02-14T11:48:40.000Z']
@ -1815,7 +1819,9 @@ assert.strictEqual(util.inspect('"\'${a}'), "'\"\\'${a}'");
[RegExp, ['foobar', 'g'], '/foobar/g'], [RegExp, ['foobar', 'g'], '/foobar/g'],
[WeakSet, [[{}]], '{ <items unknown> }'], [WeakSet, [[{}]], '{ <items unknown> }'],
[WeakMap, [[[{}, {}]]], '{ <items unknown> }'], [WeakMap, [[[{}, {}]]], '{ <items unknown> }'],
[BigInt64Array, [10], '[ 0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n ]'], [BigInt64Array,
[10],
'[\n 0n, 0n, 0n,\n 0n, 0n, 0n,\n 0n, 0n, 0n,\n 0n\n]'],
[Date, ['Sun, 14 Feb 2010 11:48:40 GMT'], '2010-02-14T11:48:40.000Z'], [Date, ['Sun, 14 Feb 2010 11:48:40 GMT'], '2010-02-14T11:48:40.000Z'],
[Date, ['invalid_date'], 'Invalid Date'] [Date, ['invalid_date'], 'Invalid Date']
].forEach(([base, input, rawExpected]) => { ].forEach(([base, input, rawExpected]) => {
@ -1996,8 +2002,8 @@ assert.strictEqual(
getset.foo = new Set([[{ a: true }, 2, {}], 'foobar', { x: 1 }]); getset.foo = new Set([[{ a: true }, 2, {}], 'foobar', { x: 1 }]);
assert.strictEqual( assert.strictEqual(
inspect(getset, { getters: true }), inspect(getset, { getters: true }),
'{ foo: [Getter/Setter] Set { [ [Object], 2, {} ], ' + '{\n foo: [Getter/Setter] Set { [ [Object], 2, {} ], ' +
"'foobar', { x: 1 } },\n inc: [Getter: NaN] }"); "'foobar', { x: 1 } },\n inc: [Getter: NaN]\n}");
} }
// Check compact number mode. // Check compact number mode.
@ -2029,8 +2035,7 @@ assert.strictEqual(
long: Array(9).fill('This text is too long for grouping!') long: Array(9).fill('This text is too long for grouping!')
}; };
let out = util.inspect(obj, { compact: 3, depth: 10 }); let out = util.inspect(obj, { compact: 3, depth: 10, breakLength: 60 });
let expected = [ let expected = [
'{', '{',
' a: {', ' a: {',

View File

@ -108,15 +108,15 @@ if (common.hasIntl) {
assert.strictEqual( assert.strictEqual(
util.inspect(dec, { showHidden: true }), util.inspect(dec, { showHidden: true }),
'TextDecoder {\n encoding: \'utf-8\',\n fatal: false,\n ' + 'TextDecoder {\n encoding: \'utf-8\',\n fatal: false,\n ' +
'ignoreBOM: true,\n [Symbol(flags)]: 4,\n [Symbol(handle)]: {} }' 'ignoreBOM: true,\n [Symbol(flags)]: 4,\n [Symbol(handle)]: {}\n}'
); );
} else { } else {
assert.strictEqual( assert.strictEqual(
util.inspect(dec, { showHidden: true }), util.inspect(dec, { showHidden: true }),
'TextDecoder {\n encoding: \'utf-8\',\n fatal: false,\n ' + "TextDecoder {\n encoding: 'utf-8',\n fatal: false,\n " +
'ignoreBOM: true,\n [Symbol(flags)]: 4,\n [Symbol(handle)]:\n ' + 'ignoreBOM: true,\n [Symbol(flags)]: 4,\n [Symbol(handle)]: ' +
'StringDecoder {\n encoding: \'utf8\',\n ' + "StringDecoder {\n encoding: 'utf8',\n " +
'[Symbol(kNativeDecoder)]: <Buffer 00 00 00 00 00 00 01> } }' '[Symbol(kNativeDecoder)]: <Buffer 00 00 00 00 00 00 01>\n }\n}'
); );
} }
} }

View File

@ -17,8 +17,7 @@ const url = new URL('https://username:password@host.name:8080/path/name/?que=ry#
assert.strictEqual( assert.strictEqual(
util.inspect(url), util.inspect(url),
`URL { `URL {
href: href: 'https://username:password@host.name:8080/path/name/?que=ry#hash',
'https://username:password@host.name:8080/path/name/?que=ry#hash',
origin: 'https://host.name:8080', origin: 'https://host.name:8080',
protocol: 'https:', protocol: 'https:',
username: 'username', username: 'username',
@ -29,13 +28,13 @@ assert.strictEqual(
pathname: '/path/name/', pathname: '/path/name/',
search: '?que=ry', search: '?que=ry',
searchParams: URLSearchParams { 'que' => 'ry' }, searchParams: URLSearchParams { 'que' => 'ry' },
hash: '#hash' }`); hash: '#hash'
}`);
assert.strictEqual( assert.strictEqual(
util.inspect(url, { showHidden: true }), util.inspect(url, { showHidden: true }),
`URL { `URL {
href: href: 'https://username:password@host.name:8080/path/name/?que=ry#hash',
'https://username:password@host.name:8080/path/name/?que=ry#hash',
origin: 'https://host.name:8080', origin: 'https://host.name:8080',
protocol: 'https:', protocol: 'https:',
username: 'username', username: 'username',
@ -49,17 +48,18 @@ assert.strictEqual(
hash: '#hash', hash: '#hash',
cannotBeBase: false, cannotBeBase: false,
special: true, special: true,
[Symbol(context)]: [Symbol(context)]: URLContext {
URLContext { flags: 2032,
flags: 2032, scheme: 'https:',
scheme: 'https:', username: 'username',
username: 'username', password: 'password',
password: 'password', host: 'host.name',
host: 'host.name', port: 8080,
port: 8080, path: [ 'path', 'name', '', [length]: 3 ],
path: [ 'path', 'name', '', [length]: 3 ], query: 'que=ry',
query: 'que=ry', fragment: 'hash'
fragment: 'hash' } }`); }
}`);
assert.strictEqual( assert.strictEqual(
util.inspect({ a: url }, { depth: 0 }), util.inspect({ a: url }, { depth: 0 }),