1
> var b1 = Buffer("d@@");
undefined
> b1.slice(1, 3)
<Buffer 40 40>
> b1.slice(1, 3) == Buffer("@@")
false

As you see the last line shows b1.slice(1, 3) is not equal to Buffer("@@"), which confuses me. Anyone would tell me the reason?

Here is buf.slice in node's doc, but it didn't solve my problem reading it.

laike9m
  • 18,344
  • 20
  • 107
  • 140
  • `b1.slice(1,3).toString('utf8') === Buffer('@@').toString('utf8') // true` ...might I also recommend `buffertools`: https://www.npmjs.org/package/buffertools – zamnuts Jun 17 '14 at 10:02
  • @zamnuts Yes converting to string then compare is the method I use for now. – laike9m Jun 17 '14 at 10:07
  • perf-wise, i'm not sure what would be faster: converting to string then comparing, or simply iterating the buffer and comparing (Buffer is iterable, just like an array, in 8-bit values, direct array access is faster in my experience) -- i'm leaning towards the latter being preferred although you'll definitely need a utility method. – zamnuts Jun 17 '14 at 10:15
  • converting to utf8 will not work, because a buffer is not necessarily a valid utf8 string. converting to hex or base64 would work, but it's ridiculous performance-wise. – vkurchatkin Jun 17 '14 at 10:36

1 Answers1

2

Buffer is an object

Equality is one of the most initially confusing aspects of JavaScript.
The behavior of == versus ===, the order of type coercions, etc. all serve to complicate the subject.

You might suppose that if two objects have the same properties and all of their properties have the same value, they would be considered equal.

Internally JavaScript actually has two different approaches for testing equality. Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference. That comparison by reference basically checks to see if the objects given refer to the same location in memory.

For example:

[ 1 , 2 , 3 ] != [ 1 , 2 , 3 ]

Read more here http://designpepper.com/blog/drips/object-equality-in-javascript.html

How to compare buffers:

Buffer comparison in Node.js

Community
  • 1
  • 1
Ilan Frumer
  • 32,059
  • 8
  • 70
  • 84