在 JavaScript 中将 ArrayBuffer 转换为字符串,可以使用 TextDecoder API。TextDecoder 可从字节序列中解码文本内容,支持多种编码格式。
以下是将 ArrayBuffer 转换为字符串的示例代码:
// 假设 ArrayBuffer 对象为 buffer
const decoder = new TextDecoder('utf-8');
const text = decoder.decode(buffer);
在上面的代码中,我们创建了一个 TextDecoder 对象,使用 utf-8
编码对 ArrayBuffer
进行解码,并将解码后的文本存储在变量 text 中。
如果 ArrayBuffer 中存储的是 GB2312
编码的文本,可以将 utf-8
编码修改为 gb2312
。
您还可以封装为函数,以便于使用:
function arrayBufferToString(buffer, encoding = 'utf-8') {
const decoder = new TextDecoder(encoding);
return decoder.decode(buffer);
}
这个函数接收两个参数,第一个参数表示要转换的 ArrayBuffer 对象,第二个参数为编码格式(默认为'utf-8')。 返回转换后的字符串。调用该函数的方式如下所示:
const buffer = new ArrayBuffer(2);
const intArray = new Uint8Array(buffer);
intArray[0] = 72;
intArray[1] = 105;
const str = arrayBufferToString(buffer);
console.log(str); // Output: Hi
01 实际问题 - 网页乱码
nodejs
使用 axios
写爬虫时 Response
乱码,经查查发现网页编码是 gb2312
的。则我们可以通过返回 arraybuffer
的方式,再重新编码即可。
const { data } = await axios.get('http://xxx.y.z', { responseType: 'arraybuffer'});
const normalStrig = arrayBufferToString(Buffer.from(data), 'gb2312'); // 返回正确的字符串