Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why is readAsBinaryString() deprecated? From W3C

The use of readAsArrayBuffer() is preferred over readAsBinaryString(), which is provided for backwards compatibility.

readAsBinaryString returns a completely different thing than the other method, so how could one be the replacement for the other?

In my specific case I have a Blob that I need to convert to base64, there are many ways, but most of them not memory efficient. As of my tests calling window.btoa() from readAsBinaryString' result works best. If I cannot use this anymore (or for now lets say "should"), then I must convert the array to a string using iteration and strings concatenation which is not memory efficient at all!

So after researching for days I don't really find an alternative to readAsBinaryString, that's why the question, or do you see an alternative that also works with 100MB blobs?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
227 views
Welcome To Ask or Share your Answers For Others

1 Answer

The history is that readAsBinaryString was present in an early specification of the FileReader API, before the ArrayBuffer interface exist.

When the ArrayBuffer interface appeared, readAsBinaryString has been deprecated because all its use cases could be done in a better way using that new interface.
Indeed, readAsBinaryString only converts the binary data into a DOMString (UTF-16). There is not much you can do from it afterward. Also, storing it as an UTF-16 string implies that it takes far more space in memory than the original data size. Add to this that strings are immutable, I guess you can see how inefficient it is to work from this.
And finally, if you really need to have this string, you can actually do the same from an ArrayBuffer, you just need to call String.fromCharCode over an Uint8 view of this ArrayBuffer.

// generate some binary data
document.createElement('canvas').toBlob(blob => {
  const bin_reader = new FileReader();
  const arr_reader = new FileReader();
  let done = 0;
  bin_reader.onload = arr_reader.onload = e => {
    if(++done===2) {
      const arr_as_bin = [...new Uint8Array(arr_reader.result)]
        .map(v => String.fromCharCode(v)).join('');
      console.log('same results: ', arr_as_bin === bin_reader.result);
      console.log(arr_as_bin);
    }
  }
  bin_reader.readAsBinaryString(blob);
  arr_reader.readAsArrayBuffer(blob);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...