Skip to content

Commit f763ac7

Browse files
BridgeARtargos
authored andcommitted
util: escape symbol and non-enumerable keys
These keys require escaping as they might also contain line breaks and other special characters. PR-URL: #22300 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: Matteo Collina <[email protected]>
1 parent 3dc3a31 commit f763ac7

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
lines changed

lib/util.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1208,9 +1208,10 @@ function formatProperty(ctx, value, recurseTimes, key, array) {
12081208
return str;
12091209
}
12101210
if (typeof key === 'symbol') {
1211-
name = `[${ctx.stylize(key.toString(), 'symbol')}]`;
1211+
const tmp = key.toString().replace(strEscapeSequencesReplacer, escapeFn);
1212+
name = `[${ctx.stylize(tmp, 'symbol')}]`;
12121213
} else if (desc.enumerable === false) {
1213-
name = `[${key}]`;
1214+
name = `[${key.replace(strEscapeSequencesReplacer, escapeFn)}]`;
12141215
} else if (keyStrRegExp.test(key)) {
12151216
name = ctx.stylize(key, 'name');
12161217
} else {

test/parallel/test-util-inspect.js

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -890,22 +890,22 @@ if (typeof Symbol !== 'undefined') {
890890
const options = { showHidden: true };
891891
let subject = {};
892892

893-
subject[Symbol('symbol')] = 42;
893+
subject[Symbol('sym\nbol')] = 42;
894894

895-
assert.strictEqual(util.inspect(subject), '{ [Symbol(symbol)]: 42 }');
895+
assert.strictEqual(util.inspect(subject), '{ [Symbol(sym\\nbol)]: 42 }');
896896
assert.strictEqual(
897897
util.inspect(subject, options),
898-
'{ [Symbol(symbol)]: 42 }'
898+
'{ [Symbol(sym\\nbol)]: 42 }'
899899
);
900900

901901
Object.defineProperty(
902902
subject,
903903
Symbol(),
904904
{ enumerable: false, value: 'non-enum' });
905-
assert.strictEqual(util.inspect(subject), '{ [Symbol(symbol)]: 42 }');
905+
assert.strictEqual(util.inspect(subject), '{ [Symbol(sym\\nbol)]: 42 }');
906906
assert.strictEqual(
907907
util.inspect(subject, options),
908-
"{ [Symbol(symbol)]: 42, [Symbol()]: 'non-enum' }"
908+
"{ [Symbol(sym\\nbol)]: 42, [Symbol()]: 'non-enum' }"
909909
);
910910

911911
subject = [1, 2, 3];
@@ -1678,3 +1678,13 @@ util.inspect(process);
16781678
assert.strictEqual(inspect(1n), '1n');
16791679
assert.strictEqual(inspect(Object(-1n)), '[BigInt: -1n]');
16801680
assert.strictEqual(inspect(Object(13n)), '[BigInt: 13n]');
1681+
1682+
// Verify non-enumerable keys get escaped.
1683+
{
1684+
const obj = {};
1685+
Object.defineProperty(obj, 'Non\nenumerable\tkey', { value: true });
1686+
assert.strictEqual(
1687+
util.inspect(obj, { showHidden: true }),
1688+
'{ [Non\\nenumerable\\tkey]: true }'
1689+
);
1690+
}

0 commit comments

Comments
 (0)