Skip to content Skip to sidebar Skip to footer

Why Is Readasbinarystring() Deprecated

Why is readAsBinaryString() deprecated? From W3C The use of readAsArrayBuffer() is preferred over readAsBinaryString(), which is provided for backwards compatibility. readAsBina

Solution 1:

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 datadocument.createElement('canvas').toBlob(blob => {
  const bin_reader = newFileReader();
  const arr_reader = newFileReader();
  let done = 0;
  bin_reader.onload = arr_reader.onload = e => {
    if(++done===2) {
      const arr_as_bin = [...newUint8Array(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);
});

Now, this method, while still very useless, has been re-added to the specs, because some websites did start using it.

And to help OP a bit more, since what they were trying to do was actually to get a base64 version of their Blob, then don't even use readAsArrayBuffer(), readAsDataURL() is what you need:

const blob = newBlob(['hello']);
const reader = newFileReader();
reader.onload = e => {
  const dataURL = reader.result;
  const base64 = dataURL.slice(dataURL.indexOf(',')+1);
  console.log(base64);
};
reader.readAsDataURL(blob);

Post a Comment for "Why Is Readasbinarystring() Deprecated"