Converting between strings and ArrayBuffers

后端 未结 24 910
慢半拍i
慢半拍i 2020-11-22 04:50

Is there a commonly accepted technique for efficiently converting JavaScript strings to ArrayBuffers and vice-versa? Specifically, I\'d like to be able to write the contents

24条回答
  •  遥遥无期
    2020-11-22 05:18

    I'd recommend NOT using deprecated APIs like BlobBuilder

    BlobBuilder has long been deprecated by the Blob object. Compare the code in Dennis' answer — where BlobBuilder is used — with the code below:

    function arrayBufferGen(str, cb) {
    
      var b = new Blob([str]);
      var f = new FileReader();
    
      f.onload = function(e) {
        cb(e.target.result);
      }
    
      f.readAsArrayBuffer(b);
    
    }
    

    Note how much cleaner and less bloated this is compared to the deprecated method... Yeah, this is definitely something to consider here.

提交回复
热议问题