Node.js API详解之 string_decoder用法实例分析
程序员文章站
2022-04-25 17:33:40
本文实例讲述了node.js api详解之 string_decoder用法。分享给大家供大家参考,具体如下:string_decoder 模块提供了一个 api,用于把 buffer 对象解码成字符...
本文实例讲述了node.js api详解之 string_decoder用法。分享给大家供大家参考,具体如下:
string_decoder 模块提供了一个 api,用于把 buffer 对象解码成字符串。
对于参数末尾不完整的多字节字符,string_decoder会将其保存在内部的buffer中,当再次解码时,补充到参数开头。
通过 const { stringdecoder } = require(‘string_decoder'); 的方式引用string_decoder模块。
目录:
- new stringdecoder([encoding])
- stringdecoder.write(buffer)
- stringdecoder.end([buffer])
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?
stringdecoder.end([buffer])
说明:
以字符串的形式返回内部 buffer 中剩余的字节,残缺的字节会被替换成符合字符编码的字符
如果提供了 buffer 参数,则在返回剩余字节之前会再执行一次 stringdecoder.write()
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 outstring = decoder.end(); console.log(outstring); // //单双字节混合,置于末尾 outstring = decoder.write(buffer.from([0x78, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67, 0xc2])); console.log(outstring); //xiaoqiang outstring = decoder.end(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.end(); console.log(outstring); //?
希望本文所述对大家node.js程序设计有所帮助。