这篇文章主要为大家展示了Node.js API中怎么使用string_decoder,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。
创新互联专注于中大型企业的成都网站设计、网站建设、外贸网站建设和网站改版、网站营销服务,追求商业策划与数据分析、创意艺术与技术开发的融合,累计客户千余家,服务满意度达97%。帮助广大客户顺利对接上互联网浪潮,准确优选出符合自己需要的互联网运用,我们将一直专注成都品牌网站建设和互联网程序开发,在前进的路上,与客户一起成长!string_decoder 模块提供了一个 API,用于把 Buffer 对象解码成字符串。
对于参数末尾不完整的多字节字符,string_decoder会将其保存在内部的buffer中,当再次解码时,补充到参数开头。
通过 const { StringDecoder } = require(‘string_decoder'); 的方式引用string_decoder模块。
目录:
new StringDecoder([encoding])
说明:
创建一个新的StringDecoder实例,可传递encoding参数作为字符编码格式,默认为'utf8′
stringDecoder.write(buffer)
说明:
返回一个解码后的字符串,并确保返回的字符串不包含残缺的多字节字符,残缺的多字节字符会被保存在一个内部的 buffer 中,
用于下次调用 stringDecoder.write() 或 stringDecoder.end()。
buffer:待解码的Buffer
demo:
const decoder = new StringDecoder('utf8'); //字符的16进制小于0x80属于单字节 let outString = decoder.write(Buffer.from([0x78, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67])); console.log(outString); //xiaoqiang //字符的16进制大于0x80属于双字节 outString = decoder.write(Buffer.from([0xC2, 0xA2])); console.log(outString); //¢ //单双字节混合,置于末尾 outString = decoder.write(Buffer.from([0x78, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67, 0xC2])); console.log(outString); //xiaoqiang outString = decoder.write(Buffer.from([0xA2])); console.log(outString); //¢ //单双字节混合,置于中间 outString = decoder.write(Buffer.from([0x78, 0x69, 0x61, 0x6f, 0x71, 0xC2, 0x69, 0x61, 0x6e, 0x67])); console.log(outString); //xiaoq?iang outString = decoder.write(Buffer.from([0xA2])); console.log(outString); //? //单双字节混合,置于开始 outString = decoder.write(Buffer.from([0xC2, 0x78, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67])); console.log(outString); //?xiaoqiang outString = decoder.write(Buffer.from([0xA2])); console.log(outString); //? //单双字节混合,置于末尾 outString = decoder.write(Buffer.from([0x78, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67, 0xC2])); console.log(outString); //xiaoqiang outString = decoder.write(Buffer.from([0x78,0xA2])); console.log(outString); //?x?