TextDecoder 的 Polyfill

Polyfill for TextDecoder

我在我的应用程序中使用 fetch and have included the whatwg-fetch polyfill

我也使用 TextDecoder as described in Jake Archibald's blog 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();

对于快速客户端测试(没有 NPM):

<script src="https://unpkg.com/text-encoding@0.6.4/lib/encoding-indexes.js"></script>
<script src="https://unpkg.com/text-encoding@0.6.4/lib/encoding.js"></script>

..然后像往常一样使用 TextDecoderMDN's example:

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/text-encoding@0.6.4/lib/encoding-indexes.js"></script>
<script src="https://unpkg.com/text-encoding@0.6.4/lib/encoding.js"></script>

现在您可以使用 FastestSmallestTextEncoderDecoder polyfill (1.5 KB), as recommended by the MDN website

如果您只想将数组解码为 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;
    }