Skip to content

Commit

Permalink
buffer: fix custom inspection with extra properties
Browse files Browse the repository at this point in the history
This broke due to a recent change that prevents exposing inspect
internals. It now relies on the public API instead and should be a
bit more robust due to that.

PR-URL: #27074
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Yongsheng Zhang <zyszys98@gmail.com>
  • Loading branch information
BridgeAR authored and danbev committed Apr 8, 2019
1 parent fadcb2d commit d834275
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 11 deletions.
26 changes: 18 additions & 8 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,7 @@ const {
isUint8Array
} = require('internal/util/types');
const {
formatProperty,
kObjectType
inspect: utilInspect
} = require('internal/util/inspect');

const {
Expand Down Expand Up @@ -665,13 +664,24 @@ Buffer.prototype[customInspectSymbol] = function inspect(recurseTimes, ctx) {
str += ` ... ${remaining} more byte${remaining > 1 ? 's' : ''}`;
// Inspect special properties as well, if possible.
if (ctx) {
let extras = false;
const filter = ctx.showHidden ? ALL_PROPERTIES : ONLY_ENUMERABLE;
str += getOwnNonIndexProperties(this, filter).reduce((str, key) => {
// Using `formatProperty()` expects an indentationLvl to be set.
ctx.indentationLvl = 0;
str += `, ${formatProperty(ctx, this, recurseTimes, key, kObjectType)}`;
return str;
}, '');
const obj = getOwnNonIndexProperties(this, filter).reduce((obj, key) => {
extras = true;
obj[key] = this[key];
return obj;
}, Object.create(null));
if (extras) {
if (this.length !== 0)
str += ', ';
// '[Object: null prototype] {'.length === 26
// This is guarded with a test.
str += utilInspect(obj, {
...ctx,
breakLength: Infinity,
compact: true
}).slice(27, -2);
}
}
return `<${this.constructor.name} ${str}>`;
};
Expand Down
2 changes: 0 additions & 2 deletions lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -1546,8 +1546,6 @@ function formatWithOptions(inspectOptions, ...args) {

module.exports = {
inspect,
formatProperty,
kObjectType,
format,
formatWithOptions
};
14 changes: 13 additions & 1 deletion test/parallel/test-buffer-inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,16 @@ assert.strictEqual(util.inspect(b), expected);
assert.strictEqual(util.inspect(s), expected);

b.inspect = undefined;
assert.strictEqual(util.inspect(b), '<Buffer 31 32, inspect: undefined>');
b.prop = new Uint8Array(0);
assert.strictEqual(
util.inspect(b),
'<Buffer 31 32, inspect: undefined, prop: Uint8Array []>'
);

b = Buffer.alloc(0);
b.prop = 123;

assert.strictEqual(
util.inspect(b),
'<Buffer prop: 123>'
);

0 comments on commit d834275

Please sign in to comment.