您好,欢迎访问一九零五行业门户网

Nodejs中使用string_decoder模块将buffer转成string

本篇文章给大家介绍一下nodejs中使用string_decoder模块将buffer转成string的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
模块简介string_decoder模块用于将buffer转成对应的字符串。使用者通过调用stringdecoder.write(buffer),可以获得buffer对应的字符串。【推荐学习:《nodejs 教程》】
它的特殊之处在于,当传入的buffer不完整(比如三个字节的字符,只传入了两个),内部会维护一个internal buffer将不完整的字节cache住,等到使用者再次调用stringdecoder.write(buffer)传入剩余的字节,来拼成完整的字符。
这样可以有效避免buffer不完整带来的错误,对于很多场景,比如网络请求中的包体解析等,非常有用。
入门例子这节分别演示了decode.write(buffer)、decode.end([buffer])两个主要api的用法。
例子一:
decoder.write(buffer)调用传入了buffer对象4906621e4f28d4de4703165e1c48080e,相应的返回了对应的字符串你;
const stringdecoder = require('string_decoder').stringdecoder;const decoder = new stringdecoder('utf8');// buffer.from('你') => <buffer e4 bd a0>const str = decoder.write(buffer.from([0xe4, 0xbd, 0xa0]));console.log(str); // 你
例子二:
当decoder.end([buffer])被调用时,内部剩余的buffer会被一次性返回。如果此时带上buffer参数,那么相当于同时调用decoder.write(buffer)和decoder.end()。
const stringdecoder = require('string_decoder').stringdecoder;const decoder = new stringdecoder('utf8');// buffer.from('你好') => <buffer e4 bd a0 e5 a5 bd>let str = decoder.write(buffer.from([0xe4, 0xbd, 0xa0, 0xe5, 0xa5]));console.log(str); // 你str = decoder.end(buffer.from([0xbd]));console.log(str); // 好
例子:分多次写入多个字节下面的例子,演示了分多次写入多个字节时,string_decoder模块是怎么处理的。
首先,传入了<buffer e4 bd a0 e5 a5>,好还差1个字节,此时,decoder.write(xx)返回你。
然后,再次调用decoder.write(buffer.from([0xbd])),将剩余的1个字节传入,成功返回好。
const stringdecoder = require('string_decoder').stringdecoder;const decoder = new stringdecoder('utf8');// buffer.from('你好') => <buffer e4 bd a0 e5 a5 bd>let str = decoder.write(buffer.from([0xe4, 0xbd, 0xa0, 0xe5, 0xa5]));console.log(str); // 你str = decoder.write(buffer.from([0xbd]));console.log(str); // 好
例子:decoder.end()时,字节数不完整的处理decoder.end(buffer)时,仅传入了好的第1个字节,此时调用decoder.end(),返回了�,对应的buffer为<buffer ef bf bd>。
const stringdecoder = require('string_decoder').stringdecoder;// buffer.from('好') => <buffer e5 a5 bd>let decoder = new stringdecoder('utf8');let str = decoder.end( buffer.from([0xe5]) );console.log(str); // �console.log(buffer.from(str)); // <buffer ef bf bd>
官方文档对于这种情况的解释是这样的(跟废话差不多),大约是约定俗成了,当utf8码点无效时,替换成ef bf bd。
returns any remaining input stored in the internal buffer as a string. bytes representing incomplete utf-8 and utf-16 characters will be replaced with substitution characters appropriate for the character encoding.
相关链接你应该记住的一个utf-8字符「ef bf bd」http://liudanking.com/golang/utf-8_replacement_character/
更多编程相关知识,请访问:编程视频!!
以上就是nodejs中使用string_decoder模块将buffer转成string的详细内容。
其它类似信息

推荐信息