13 lines
570 B
TypeScript
13 lines
570 B
TypeScript
// 网络 txt 常是 GBK/GB2312 而服务端一律标 charset=utf-8:先严格试 UTF-8,
|
|
// 失败回退 GB18030(GBK 超集);UTF-16 靠 BOM 识别。纯逻辑,vitest 覆盖。
|
|
export function decodeText(buf: ArrayBuffer): string {
|
|
const b = new Uint8Array(buf);
|
|
if (b[0] === 0xff && b[1] === 0xfe) return new TextDecoder("utf-16le").decode(b);
|
|
if (b[0] === 0xfe && b[1] === 0xff) return new TextDecoder("utf-16be").decode(b);
|
|
try {
|
|
return new TextDecoder("utf-8", { fatal: true }).decode(b);
|
|
} catch {
|
|
return new TextDecoder("gb18030").decode(b);
|
|
}
|
|
}
|