Converting between strings and ArrayBuffers

后端 未结 24 878
慢半拍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:06

    For node.js and also for browsers using https://github.com/feross/buffer

    function ab2str(buf: Uint8Array) {
      return Buffer.from(buf).toString('base64');
    }
    function str2ab(str: string) {
      return new Uint8Array(Buffer.from(str, 'base64'))
    }
    

    Note: Solutions here didn't work for me. I need to support node.js and browsers and just serialize UInt8Array to a string. I could serialize it as a number[] but that occupies unnecessary space. With that solution I don't need to worry about encodings since it's base64. Just in case other people struggle with the same problem... My two cents

提交回复
热议问题