I was expecting that new Buffer(buffer.toString()) would always be byte-for-byte equal. However, I am encountering a case where it is not true.
First, a case where it is true:
var buf1 = new Buffer(32);
for (var i = 0 ; i < 32 ; i++) {
buf1[i] = i;
}
console.log(buf1);
console.log(new Buffer(buf1.toString()));
<Buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f>
<Buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f>
However, here is a case where it is not true:
var buf2 = crypto.createHmac('sha256', 'key')
.update('string')
.digest();
console.log(buf2);
console.log(new Buffer(buf2.toString()));
<Buffer 97 d1 5b ea ba 06 0d 07 38 ec 75 9e a3 18 65 17 8a b8 bb 78 1b 2d 21 07 64 4b a8 81 f3 99 d8 d6>
<Buffer ef bf bd ef bf bd 5b ef bf bd ef bf bd 06 0d 07 38 ef bf bd 75 ef bf bd ef bf bd 18 65 17 ef bf bd ef bf bd ef bf bd 78 1b 2d 21 07 64 4b ef bf bd ef ... >
What is different about buf2 that makes new Buffer(buf2.toString()) not byte-equivalent to buf2?
utf8, and thennew Buffer(str)decodesutf8by default—I thought. ThetoString()implementation here isBuffer.prototype.toString().Buffer().