There are two different Buffer objects (different values) in a JavaScript, but in JavaScript object, they are treated as being equal. Any idea why? How to force them to be different keys for a JavaScript? Thanks
my node.js version is 10.15.1 on Ubuntu 18.04.
var buf1 = Buffer.from([
10,
33,
45,
77,
10,
33,
46,
166,
140,
190,
5,
241
]);
var buf2 = new Buffer.from([
10,
33,
45,
77,
10,
33,
46,
168,
215,
216,
5,
241
]);
let a = {};
a[buf2] = "jon";
console.log(a[buf1]); //output jon
>Solution :
a[buf2] is equivalent to a[buf2.toString()], which is equivalent to a[buf2.toString('utf-8')], which is the cause of your problem: your buffers don’t hold valid UTF-8 data, so when converting to an UTF-8 string, invalid code points are replaced by the Unicode replacement character, U+FFFD (encoded as 0xEF 0xBF 0xBD in UTF-8).
To show this, you can run the following code:
console.log('buf1', Buffer.from(buf1.toString()).toString('hex'));
console.log('buf2', Buffer.from(buf2.toString()).toString('hex'));
The result is the hexadecimal representation of each buffer as it’s used as a property "name" (replacement character highlighted):
buf1 0a212d4d0a212eefbfbdefbfbdefbfbd05efbfbd
^^^^^^^^^^^^^^^^^^ ^^^^^^
buf2 0a212d4d0a212eefbfbdefbfbdefbfbd05efbfbd
As you can see, they are equivalent.