Skip to main content
Buffer.compare - node__buffer.d.ts - Node documentation
method Buffer.compare

Usage in Deno

```typescript import { type Buffer } from "node:node__buffer.d.ts"; ```
Buffer.compare(
target: Uint8Array,
targetStart?: number,
targetEnd?: number,
sourceStart?: number,
sourceEnd?: number,
):
-1
| 0
| 1
Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. Comparison is based on the actual sequence of bytes in each `Buffer`. * `0` is returned if `target` is the same as `buf` * `1` is returned if `target` should come _before_`buf` when sorted. * `-1` is returned if `target` should come _after_`buf` when sorted. ```js import { Buffer } from 'node:buffer'; const buf1 = Buffer.from('ABC'); const buf2 = Buffer.from('BCD'); const buf3 = Buffer.from('ABCD'); console.log(buf1.compare(buf1)); // Prints: 0 console.log(buf1.compare(buf2)); // Prints: -1 console.log(buf1.compare(buf3)); // Prints: -1 console.log(buf2.compare(buf1)); // Prints: 1 console.log(buf2.compare(buf3)); // Prints: 1 console.log([buf1, buf2, buf3].sort(Buffer.compare)); // Prints: [ , , ] // (This result is equal to: [buf1, buf3, buf2].) ``` The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. ```js import { Buffer } from 'node:buffer'; const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); console.log(buf1.compare(buf2, 5, 9, 0, 4)); // Prints: 0 console.log(buf1.compare(buf2, 0, 6, 4)); // Prints: -1 console.log(buf1.compare(buf2, 5, 6, 5)); // Prints: 1 ``` `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`.

Parameters

target: Uint8Array
A `Buffer` or Uint8Array with which to compare `buf`.
optional
targetStart: number = 0
The offset within `target` at which to begin comparison.
optional
targetEnd: number = target.length
The offset within `target` at which to end comparison (not inclusive).
optional
sourceStart: number = 0
The offset within `buf` at which to begin comparison.
optional
sourceEnd: number = buf.length
The offset within `buf` at which to end comparison (not inclusive).

Return Type

-1
| 0
| 1