Nodejs中如何使用string_decoder模块将缓冲区转成字符串

  介绍

小编给大家分享一下Nodejs中如何使用string_decoder模块将缓冲区转成字符串,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!

  本篇文章给大家介绍一下Nodejs中使用string_decoder模块将缓冲区转成字符串的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

 Nodejs中如何使用string_decoder模块将缓冲区转成字符串

<强>模块简介

<代码> string_decoder 模块用于将缓冲区转成对应的字符串。使用者通过调用<代码> stringDecoder.write(缓冲)>

它的特殊之处在于,当传入的缓冲区不完整(比如三个字节的字符,只传入了两个),内部会维护一个内部缓冲区将不完整的字节缓存住,等到使用者再次调用<代码> stringDecoder.write(缓冲)传入剩余的字节,来拼成完整的字符。

这样可以有效避免缓冲不完整带来的错误,对于很多场景,比如网络请求中的包体解析等,非常有用。

<强>入门例子

这节分别演示了<代码> decode.write(缓冲),<代码> decode.end((缓冲))>

例子一:

<代码> decoder.write(缓冲)调用传入了缓冲对象<代码> & lt;缓冲e4 bd a0> 你> const  StringDecoder =,要求(& # 39;string_decoder& # 39;) .StringDecoder;   const  decoder =, new  StringDecoder (& # 39; use utf8 # 39;);//,Buffer.from(& # 39;你& # 39;),=祝辞,& lt; Buffer  e4  bd  a0>   const  str =, decoder.write (Buffer.from ([0 xe4, 0 xbd,, 0 xa0]));   console.log (str);,,//,你以前

例子二:

当<代码> decoder.end((缓冲))> 参数,那么相当于同时调用<代码> decoder.write(缓冲)和<代码> decoder.end()

const  StringDecoder =,要求(& # 39;string_decoder& # 39;) .StringDecoder;   const  decoder =, new  StringDecoder (& # 39; use utf8 # 39;);//,Buffer.from(& # 39;你好& # 39;),=祝辞,& lt; Buffer  e4  bd  a0  e5  a5  bd>   let  str =, decoder.write (Buffer.from ([0 xe4, 0 xbd,, 0 xa0, 0 xe5, 0 xa5]));   console.log (str);,,//你      时间=str  decoder.end (Buffer.from ([0 xbd]));   console.log (str);,,//,好 <>强例子:分多次写入多个字节

下面的例子,演示了分多次写入多个字节时,<代码> string_decoder 模块是怎么处理的。

首先,传入了<代码> & lt;缓冲e4 bd a0 e5 a5> ,<代码>好> decoder.write (xx) 返回<代码>你>

然后,再次调用<代码> decoder.write (Buffer.from ([0 xbd]))> 好> const  StringDecoder =,要求(& # 39;string_decoder& # 39;) .StringDecoder;   const  decoder =, new  StringDecoder (& # 39; use utf8 # 39;);//,Buffer.from(& # 39;你好& # 39;),=祝辞,& lt; Buffer  e4  bd  a0  e5  a5  bd>   let  str =, decoder.write (Buffer.from ([0 xe4, 0 xbd,, 0 xa0, 0 xe5, 0 xa5]));   console.log (str);,,//你      时间=str  decoder.write (Buffer.from ([0 xbd]));   console.log (str);,,//,好 <>强例子:decoder.end()时,字节数不完整的处理

<代码> decoder.end(缓冲)时,仅传入了<代码>好> decoder.end() ,返回了<代码> ?> & lt;缓冲ef bf bd>

const  StringDecoder =,要求(& # 39;string_decoder& # 39;) .StringDecoder;//,Buffer.from(& # 39;好& # 39;),=祝辞,& lt; Buffer  e5  a5  bd>   let  decoder =, new  StringDecoder (& # 39; use utf8 # 39;);   let  str =, decoder.end (, Buffer.from ([0 xe5]),);   console.log (str);,,//, ?   console.log (Buffer.from (str));,,//, & lt; Buffer  ef  bf  bd>

官方文档对于这种情况的解释是这样的(跟废话差不多),大约是约定俗成的了,当

Nodejs中如何使用string_decoder模块将缓冲区转成字符串