//把buf里的内容copy到b里面,从0开始copy,copy到末尾(三个字节打印一个汉字,此处是5个一打印,会出现乱码)
const buf=Buffer.from('中文字符串!');
for (let i=0; i<buf.length;i+=5){
const b=Buffer.allocUnsafe(5);
buf.copy(b,0,i);
console.log(b.toString());
}
如何解决呢
引入
//引入StringDecoder,使用utf8的格式输出;
const { StringDecoder }=require('string_decoder');
//自定义一个decoder,以我们希望的方式输出;
const decoder=new StringDecoder('utf8');
const buf=Buffer.from('中文字符串');
for (let i=0; i<buf.length;i+=5){
const b=Buffer.allocUnsafe(5);
buf.copy(b,0,i);
console.log(decoder.write(b));
}