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
2
Answers
a[buf2] = "jon";
is exactly the same asa['[object: Object]'] = "jon";
, because key of object must be astring
, if it’s notstring
it will be converted to string usingtoString
method.What you wanted to do is:
a[buf2]
is equivalent toa[buf2.toString()]
, which is equivalent toa[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:
The result is the hexadecimal representation of each buffer as it’s used as a property "name" (replacement character highlighted):
As you can see, they are equivalent.