Skip to content
Tutorials Center
My learning

Topics

Node.js Reference Β· Buffers and Encoding

Node.js Buffer.compare() and equals() methods

Reference for Buffer.compare(), buf.compare() and buf.equals() in Node.js: byte-wise ordering, sorting buffers, range arguments and why equals() is not constant time.

Three related tools compare buffers byte by byte. buf.equals(other) answers "same bytes?" with a boolean. Buffer.compare(a, b) and buf.compare(other) answer "which comes first?" with -1, 0 or 1, which makes them directly usable as a sort comparator.

Comparison is lexicographic on raw byte values from 0 to 255: the first differing byte decides, and if one buffer is a prefix of the other, the shorter one is smaller. No text rules apply, so it is not alphabetical order for non-ASCII text.

NODE
Buffer.compare(Buffer.from('a'), Buffer.from('b'));    // -1
Buffer.from('abc').equals(Buffer.from('abc'));         // true

Try it

Node.js Ordering and equality

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Comparing ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
Buffer.compare(buf1, buf2)
buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])
buf.equals(otherBufferOrUint8Array)
Name Description
buf1, buf2 Buffers or Uint8Arrays to compare.
target The buffer to compare against.
targetStart, targetEnd Range within target (default 0 and target.length).
sourceStart, sourceEnd Range within buf (default 0 and buf.length).

Returns: compare() returns 0 if the bytes are equal, 1 if the first sorts after the second, and -1 if it sorts before. equals() returns a boolean.

Errors: ERR_INVALID_ARG_TYPE when an argument is not a Buffer or Uint8Array; ERR_OUT_OF_RANGE for range values outside the buffers.

Usage notes

  • buffers.sort(Buffer.compare) sorts an array of buffers in byte order without any wrapper.
  • The compare() ranges apply to both sides independently, and the lengths compared may differ; a shorter range is a prefix.
  • equals() and compare() stop at the first difference, so their running time leaks how many leading bytes match. Do not use them to verify secrets such as tokens or MACs; use crypto.timingSafeEqual() instead (it requires equal lengths).
  • equals() returns false immediately when lengths differ.
  • The === operator compares buffer identity, not content: two buffers with the same bytes are not ===.
  • For strings that were encoded with different encodings, decode them to a common form first; equal text can have different bytes.