How to compare two blobs in JavaScript?

6.1k views Asked by At

I load two blob files in JavaScript using the code below.

I want to compare them to see if they are precisely the same.

(blob1 === blob2) is returning false, even though the reported size of each blob is 574 bytes. What am I doing wrong?

  getHTTPAsBlob(url, callback) {
    let cacheBust = Math.random().toString()
    url = url + '?&cachebust=' + cacheBust
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function (e) {
      if (xhr.status == 200) {
        // get binary data as a response
        let fileData = this.response;
        let contentType = xhr.getResponseHeader("content-type")
        var reader = new FileReader()
        reader.onload = (e) => {
          console.log(reader.result)
          console.log(fileData)
          callback(null, {
              Body: reader.result,
              Blob: fileData,
              ContentType: contentType,
              Etag: null,
              LastModified: null,
            })
        }
        reader.readAsText(fileData)
        } else {
        callback(xhr)
      }
      }
      xhr.send();
    }
5

There are 5 answers

0
Michael On

Unfortunately, this is a case of comparing two completely independent pointers that reference comparable content. To see how this might work for simpler content, try the following in the javascript console:

new Number(5) == new Number(5)

Returns false. Frustrating that 5 as an object does not equal an object whose value is 5. But at least this puts Blob into context.

I'm running into this same problem, and agree with the previous suggestion that FileReader is the only option.

0
MrViK On

You must use a FileReader to compare them

The documentation for FileReader is on MDN. Take a look at methods to choose what's best for your data.

A useless way of comparing two blobs is looking at their size. Although two blobs of the same size will return true no matter their content.

Example

new Blob([Math.random()]).size == new Blob([Math.random()]).size // true.

1
김광훈 On

I think "blob compare" plug-in will be help you. It can compare blob size,type and so on. https://www.npmjs.com/package/blob-compare

but I don't know if this plug-in is the perfect way.

0
bmaupin On

The question was asked in context of JavaScript in the browser, but in case anyone wants to compare blobs in Node.js:

const areBlobsEqual = async (blob1, blob2) => {
  return !Buffer.from(await blob1.arrayBuffer()).compare(
    Buffer.from(await blob2.arrayBuffer())
  );
};
0
zhuhang.jasper On

See this answer to a similar question: https://stackoverflow.com/a/77342813/6122411

In short, it is to Convert the File/Blob to ArrayBuffer using FileReader. Then perform byte-to-byte check on the buffer. A library is recommended in that above answer.