how to convert arraybuffer to string

前端 未结 4 807
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 21:26

I have written a simple TCP server on node.js to send some data to a Chrome app. In the chrome app, when I get the data, I convert that to string using below function, I get

4条回答
  •  长发绾君心
    2021-01-14 22:09

    There is an asynchronous way using Blob and FileReader.

    You can specify any valid encoding.

    function arrayBufferToString( buffer, encoding, callback ) {
        var blob = new Blob([buffer],{type:'text/plain'});
        var reader = new FileReader();
        reader.onload = function(evt){callback(evt.target.result);};
        reader.readAsText(blob, encoding);
    }
    
    //example:
    var buf = new Uint8Array([65,66,67]);
    arrayBufferToString(buf, 'UTF-8', console.log.bind(console)); //"ABC"
    

提交回复
热议问题