Buffer转字符串后map方法展示关键词异常问题求助
问题解决:Buffer处理UTF-16LE字节数组导致的字符串异常
问题根源
你的关键词字节数组是UTF-16LE编码(每个可见字符后跟一个0字节,比如79,0对应字符'O'),直接用默认的buffer.toString()(utf8编码)解码时,会把0字节解析成不可见的空字符\x00。这些隐藏的空字符肉眼看不到,但会导致后续字符串处理(比如split、传递到主函数)出现异常,最终让map渲染失效。
解决方案
1. 正确解码字节数组
指定用utf16le编码解码,直接得到无隐藏空字符的干净字符串:
const Keywords = [79, 0, 98, 0, 115, 0, 116, 0, 59, 0, 80, 0, 101, 0, 114, 0, 115, 0, 111, 0, 110, 0, 59, 0]; const buffer = Buffer.from(Keywords); // 用utf16le解码,得到正常字符串 const bufferString = buffer.toString('utf16le'); // 输出:"Obst;Person;"
2. 处理split后的空元素
split(";")会生成末尾的空字符串,用filter(Boolean)过滤掉无效项:
const words = bufferString.split(";").filter(Boolean); // 输出:["Obst", "Person"]
3. 验证并传递数组
此时得到的words数组和手动创建的完全一致,传递到主函数用map渲染就能正常显示所有关键词。
完整验证代码
const Keywords = [79, 0, 98, 0, 115, 0, 116, 0, 59, 0, 80, 0, 101, 0, 114, 0, 115, 0, 111, 0, 110, 0, 59, 0]; const buffer = Buffer.from(Keywords); const bufferString = buffer.toString('utf16le'); const words = bufferString.split(";").filter(Boolean); // 主函数中map渲染示例 words.map(word => console.log(word)); // 输出: // Obst // Person
内容的提问来源于stack exchange,提问作者Broump
相关产品推荐
相关产品推荐

