概述TextEncoder/TextDecoder 提供将字符串与字节之间转换的能力,默认使用 UTF-8。与 Encoding Streams 搭配可在流式读取与上传中进行转换与压缩协作。示例const enc = new TextEncoder() const buf = enc.encode('你好 world') const dec = new TextDecoder('utf-8', { fatal: false }) console.log(dec.decode(buf)) // Encoding Streams(示意):将可读流转换为文本 const readableText = new TextDecoderStream() const resp = await fetch('/data.bin') await resp.body.pipeThrough(readableText).pipeTo(new WritableStream({ write(chunk) { console.log(chunk) } })) 工程建议错误处理:选择合适的错误模式(`fatal`)与替换字符策略;避免乱码。性能:避免重复转换与不必要的复制;在大数据场景使用流式接口。兼容:在不支持 Encoding Streams 的浏览器回退到分片解码。参考与验证MDN TextEncoder/TextDecoder 文档:https://developer.mozilla.org/docs/Web/API/TextEncoderMDN Encoding Streams 文档:https://developer.mozilla.org/docs/Web/API/EncodingWHATWG Streams 规范:https://streams.spec.whatwg.org/

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部