From 48583c4207dbe9c9a7f1c85ab2a5117a2d258c9c Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 27 Feb 2017 23:56:39 -0800 Subject: [PATCH 1/2] test: add test-buffer-prototype-inspect lib/buffer.js defines Buffer.prototype.inspect() to override how buffers are presented by util.inspect(). Add basic tests for it. --- .../parallel/test-buffer-prototype-inspect.js | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 test/parallel/test-buffer-prototype-inspect.js diff --git a/test/parallel/test-buffer-prototype-inspect.js b/test/parallel/test-buffer-prototype-inspect.js new file mode 100644 index 00000000000000..5f65a9bb288f16 --- /dev/null +++ b/test/parallel/test-buffer-prototype-inspect.js @@ -0,0 +1,23 @@ +'use strict'; +require('../common'); + +// lib/buffer.js defines Buffer.prototype.inspect() to override how buffers are +// presented by util.inspect(). + +const assert = require('assert'); +const util = require('util'); + +{ + const buf = Buffer.from('fhqwhgads'); + assert.strictEqual(util.inspect(buf), ''); +} + +{ + const buf = Buffer.from(''); + assert.strictEqual(util.inspect(buf), ''); +} + +{ + const buf = Buffer.from('x'.repeat(51)); + assert.ok(/^$/.test(util.inspect(buf))); +} From 03b1a2d42bab6da8f9326a97c0f186f5deeb78bf Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 28 Feb 2017 00:15:07 -0800 Subject: [PATCH 2/2] buffer: refactor Buffer.prototype.inspect() Replace toString().match().join() with toString().replace().trim(). This enables the elimination of a length check becuase replace() will return empty string if Buffer is empty whereas match() returns null. --- lib/buffer.js | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index b6928c18f8ded3..d4f6ccff7e2fe2 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -531,12 +531,10 @@ Buffer.prototype.equals = function equals(b) { Buffer.prototype[internalUtil.customInspectSymbol] = function inspect() { var str = ''; var max = exports.INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) - str += ' ... '; - } - return '<' + this.constructor.name + ' ' + str + '>'; + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); + if (this.length > max) + str += ' ... '; + return `<${this.constructor.name} ${str}>`; }; Buffer.prototype.inspect = Buffer.prototype[internalUtil.customInspectSymbol];