Polyfill for TextDecoder

I use fetchand have included whatwg-fetchpolyfill in my application.

I also use TextDecoderas described on Jake Archibald's blog . So get it out! to decode the response, but I'm not sure which polyfill to use.

(Currently Safari complains about ReferenceError: Can't find variable: TextDecoder)

I suppose there is a polyfill for TextDecoder, but I do not find it ...

+8
source share
2 answers

I managed to solve this problem using the library text-encoding

npm install text-encoding --save

together with

import encoding from 'text-encoding';
const decoder = new encoding.TextDecoder();
+11
source

For quick client-side testing (without 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>

..and then use TextDecoderas usual. MDN 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>
Run codeHide result

+7
source

Source: https://habr.com/ru/post/1661096/


All Articles