在轉換 arraybuffer 為 String 時, 出錯, length 小的時候, 不會出問題, 但大量時就出錯了:
Maximum call stack size exceeded
To work around the problem you could batch the calls to String.fromCharCode
. Don’t call it just once, but call it once for every 1024 entries, for example, and then concatenate the resulting strings.
會造成錯誤的程式碼:
let data_array = pako.inflate(raw);
let str = String.fromCharCode.apply(null, new Uint16Array(data_array))
改寫成, 不會出錯的版本:
let str = '';
const chunk = 8 * 1024
let i;
for (i = 0; i < data_array.length / chunk; i++) {
str += String.fromCharCode.apply(null, data_array.slice(i * chunk, (i + 1) * chunk));
}
str += String.fromCharCode.apply(null, data_array.slice(i * chunk));
相關討論:
Converting arraybuffer to string : Maximum call stack size exceeded
https://stackoverflow.com/questions/38432611/converting-arraybuffer-to-string-maximum-call-stack-size-exceeded
I finally used this code:
function _arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}