Buffer Comparison
You'll learn how to compare two Buffers for equality and ordering using built-in methods.
The Core Idea
When working with binary data, you often need to check if two Buffers contain identical bytes or determine their relative ordering (like sorting strings alphabetically, but for binary data). Node.js provides specific methods for these comparisons because you can't reliably use === or comparison operators on Buffer objects.
Checking for Equality
Use buf1.equals(buf2) to test if two Buffers contain exactly the same bytes:
const buf1 = Buffer.from('hello');
const buf2 = Buffer.from('hello');
const buf3 = Buffer.from('world');
console.log(buf1.equals(buf2)); // true
console.log(buf1.equals(buf3)); // false
console.log(buf1 === buf2); // false (different objects!)
Even though buf1 and buf2 contain identical data, === returns false because they're different objects in memory. The equals() method compares contents, not identity.
Lexicographic Ordering
Use buf1.compare(buf2) to determine ordering, similar to sorting strings:
const a = Buffer.from('abc');
const b = Buffer.from('abd');
const c = Buffer.from('abc');
console.log(a.compare(b)); // -1 (a comes before b)
console.log(b.compare(a)); // 1 (b comes after a)
console.log(a.compare(c)); // 0 (equal)
The result tells you: negative = first comes before second, zero = equal, positive = first comes after second. This is lexicographic ordering—comparing byte by byte, just like dictionary order for strings.
Key Takeaway: Use equals() to check if Buffers have identical contents, and compare() for lexicographic ordering—both methods compare actual bytes, not object references.