TextDecoder 的 Polyfill

问题描述 投票:0回答:5

我正在使用

fetch
并在我的应用程序中包含了
whatwg-fetch
polyfill

我还使用了

TextDecoder
,如 Jake Archibald 的博客中所述 That's so fetch! 来解码响应,但我不确定要使用什么 polyfill。

(目前 Safari 抱怨

ReferenceError: Can't find variable: TextDecoder

我猜

TextDecoder
有一个polyfill,但我没有找到它......

javascript fetch-api polyfills
5个回答
15
投票

我能够通过使用

text-encoding
库解决这个问题

npm install text-encoding --save

一起
import encoding from 'text-encoding';
const decoder = new encoding.TextDecoder();

8
投票

现在您可以按照 MDN 网站的推荐使用 FastestSmallestTextEncoderDecoder polyfill (1.5 KB)。


7
投票

用于快速客户端测试(无需 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>


0
投票
  • 文本编码:当前第一个批准的答案引用了已弃用的包
  • FastestSmallestTextEncoderDecoder:使用此包时我遇到了与没有此包时相同的问题。它是最小且最快的,因此您仍然可以考虑它。他们在 github 自述文件中对为什么它们是最好的进行了很好的比较。

我的推荐是text-encoding-shim: https://www.npmjs.com/package/text-encoding-shim

我尝试了一些东西,最终这个尺寸并不大,并且致力于使用我的库和玩笑测试。也许不是最好的,但我在我的选择上浪费了相当多的时间,所以也许它对某人有帮助。


-1
投票

如果您只想将数组解码为 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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.