fetch
并在我的应用程序中包含了 whatwg-fetch
polyfill。
TextDecoder
,如 Jake Archibald 的博客中所述 That's so fetch! 来解码响应,但我不确定要使用什么 polyfill。
(目前 Safari 抱怨
ReferenceError: Can't find variable: TextDecoder
)
我猜
TextDecoder
有一个polyfill,但我没有找到它......
text-encoding
库解决这个问题
npm install text-encoding --save
与
一起import encoding from 'text-encoding';
const decoder = new encoding.TextDecoder();
现在您可以按照 MDN 网站的推荐使用 FastestSmallestTextEncoderDecoder polyfill (1.5 KB)。
用于快速客户端测试(无需 NPM):
<script src="https://unpkg.com/[email protected]/lib/encoding-indexes.js"></script>
<script src="https://unpkg.com/[email protected]/lib/encoding.js"></script>
..然后像平常一样使用
TextDecoder
。 MDN 的示例:
var win1251decoder = new TextDecoder('windows-1251');
var bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
console.log(win1251decoder.decode(bytes)); // Привет, мир!
<script src="https://unpkg.com/[email protected]/lib/encoding-indexes.js"></script>
<script src="https://unpkg.com/[email protected]/lib/encoding.js"></script>
我的推荐是text-encoding-shim: https://www.npmjs.com/package/text-encoding-shim
我尝试了一些东西,最终这个尺寸并不大,并且致力于使用我的库和玩笑测试。也许不是最好的,但我在我的选择上浪费了相当多的时间,所以也许它对某人有帮助。
如果您只想将数组解码为 utf8,只需添加一个函数,无需外部库:
function Utf8ArrayToStr(array) {
var out, i, len, c;
var char2, char3;
out = "";
len = array.length;
i = 0;
while(i < len) {
c = array[i++];
switch(c >> 4)
{
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 0xxxxxxx
out += String.fromCharCode(c);
break;
case 12: case 13:
// 110x xxxx 10xx xxxx
char2 = array[i++];
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
return out;
}