Spaces:
Sleeping
Sleeping
File size: 1,767 Bytes
de5ba48 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | 'use strict'
let TextDecoder
try {
TextDecoder = require('util').TextDecoder
} catch (e) { }
const { TextDecoder: PolyfillTextDecoder, getEncoding } = require('text-decoding')
// Node has always utf-8
const textDecoders = new Map()
if (TextDecoder) {
textDecoders.set('utf-8', new TextDecoder('utf-8'))
} else {
textDecoders.set('utf-8', new PolyfillTextDecoder('utf-8'))
}
textDecoders.set('utf8', textDecoders.get('utf-8'))
function decodeText (text, textEncoding, destEncoding) {
if (text) {
if (textDecoders.has(destEncoding)) {
try {
return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
} catch (e) { }
} else {
try {
textDecoders.set(destEncoding, new TextDecoder(destEncoding))
return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
} catch (e) {
if (getEncoding(destEncoding)) {
try {
textDecoders.set(destEncoding, new PolyfillTextDecoder(destEncoding))
return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
} catch (e) { }
}
}
}
}
return text
}
function decodeTextPolyfill (text, textEncoding, destEncoding) {
if (text) {
if (textDecoders.has(destEncoding)) {
try {
return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
} catch (e) { }
} else {
if (getEncoding(destEncoding)) {
try {
textDecoders.set(destEncoding, new PolyfillTextDecoder(destEncoding))
return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
} catch (e) { }
}
}
}
return text
}
module.exports = TextDecoder ? decodeText : decodeTextPolyfill
|