Search code examples
javascriptarraysnode.jsarraybuffer

How to convert Buffer array to hex?


I am getting a Buffer array back in a JSON object when I call one of my API endpoints. I would like to convert this array to a more "usable" form (hex?) so I can compare them, etc. Here is what the object currently looks like:

"hash": {
  "type": "Buffer",
  "data": [
    151,
    14,
    51,
    26,
    46,
    52,
    5,
    151,
    99,
    107,
    38,
    188,
    138,
    180,
    76,
    56,
    108,
    214,
    135,
    213,
    125,
    134,
    105,
    139,
    129,
    236,
    206,
    157,
    67,
    1,
    12,
    12
  ]
}

How would I go about converting this array to a hex (or string, etc.) so that I can compare hashes?


Solution

  • You can just create a new buffer and convert it into the format you need.

    var o = {"hash": {
    "type": "Buffer",
    "data": [
      151,
      14,
      51,
      26,
      46,
      52,
      5,
      151,
      99,
      107,
      38,
      188,
      138,
      180,
      76,
      56,
      108,
      214,
      135,
      213,
      125,
      134,
      105,
      139,
      129,
      236,
      206,
      157,
      67,
      1,
      12,
      12
      ]
     }
    }
    
    console.log(new Buffer(o.hash,'hex').toString('hex'));
    // 970e331a2e340597636b26bc8ab44c386cd687d57d86698b81ecce9d43010c0c