微信小程序中Buffer转UTF8字符串
背景
在开发大模型的流式返回接口时,需要将后端返回的二进制流转化为字符串。关于这个问题,在大多数情况下,我们可借助 TextDecoder 来达成。
TextDecoder 是一个内置的 JavaScript 对象,它能够把 ArrayBuffer 转换为字符串。
但是!在微信小程序中是不支持该对象的。因为我们需要借助下面这个函数去实现。
export function jm(data) {
let txt;
// 进行判断返回的对象是Uint8Array(开发者工具)或者ArrayBuffer(真机)
// 1.获取对象的准确的类型
const type = Object.prototype.toString.call(data); // Uni8Array的原型对象被更改了所以使用字符串的信息进行判断。
if (type === "[object Uint8Array]") {
txt = decodeURIComponent(escape(String.fromCharCode(...data)))
} else if (data instanceof ArrayBuffer) {
// 将ArrayBuffer转换为Uint8Array
const uint8Array = new Uint8Array(data);
txt = decodeURIComponent(escape(String.fromCharCode(...uint8Array)))
}
// 打印编码的结果
return txt;
}
代码详解
(1)获取数据类型:
Object.prototype.toString.call(data)
:通过 Object.prototype.toString 方法获取 data 的准确类型。之所以不直接使用 data instanceof Uint8Array 是因为 Uint8Array 的原型对象可能被更改,使用这种方式可以确保获取到准确的类型信息。
(2)处理 Uint8Array 类型的数据:
if (type === "[object Uint8Array]")
:如果 data 的类型是 Uint8Array,则执行以下操作:String.fromCharCode(...data)
:使用扩展运算符 … 将 Uint8Array 中的每个元素展开,然后通过 String.fromCharCode 方法将每个元素(即字节)转换为对应的 Unicode 字符。escape
:对转换后的字符串进行 escape 编码,将非 ASCII 字符转换为 %xx 或 %uxxxx 形式。decodeURIComponent
:对 escape 编码后的字符串进行解码,将其转换为原始的中文字符串。
处理 ArrayBuffer 类型的数据:else if (data instanceof ArrayBuffer)
:如果 data 的类型是 ArrayBuffer,则执行以下操作:const uint8Array = new Uint8Array(data);
:将 ArrayBuffer 转换为 Uint8Array,以便后续处理。
后续处理步骤与处理 Uint8Array 类型的数据相同。