I\'m new in Node.js. There aren\'t Buffer comparison and I should use modules like buffertools for these feature.
But I see a pretty strange behaviour when I compa
There's already an accepted answer but I thought I might still as well chime in with a remark since I don't find the accepted answer particularly clear or helpful. It's even incorrect if only because it answers questions that the OP didn't ask. So let's boil that down:
> var b1 = new Buffer([170]);
> var b2 = new Buffer([171]);
> b1 < b2
> b1 > b2
> b1 == b2
All that is asked for is: "how do I perform equivalence and less than / greater than comparison (a.k.a. (total) ordering) on buffers".
The answer is:
either do it manually by stepping through all the bytes of both buffers and perform a comparison between the corresponding bytes, e.g. b1[ idx ] === b2[ idx ]
,
or use Buffer.compare( b1, b2 )
which gives you one of -1
, 0
, or +1
, depending on whether the first buffer would sort before, exactly like, or after the second (sorting a list d
that contains buffers is then as easy as d.sort( Buffer.compare )
).
Observe I use ===
in my first example; my frequent comments on this site concerning the abuse of ==
in JavaScript should make it abundantly clear why that is so.