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


当前第2页 返回上一页

首先,传入了<Buffer e4 bd a0 e5 a5>还差1个字节,此时,decoder.write(xx)返回

然后,再次调用decoder.write(Buffer.from([0xbd])),将剩余的1个字节传入,成功返回

1

2

3

4

5

6

7

8

9

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>

1

2

3

4

5

6

7

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的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

谈谈使用nodejs增删改查本地json文件的方法

初步了解nodejs中的异步i/o

怎么看nodejs是否安装成功

23个需要了解的十分有用的nodejs库(推荐)

vue nodejs 什么区别

nodejs有什么用?

浅谈nodejs中的多线程操作

为什么node.js要引入buffer?浅析缓冲区buffer

nodejs+robotjs实现控制鼠标键盘功能

浅谈npm邮箱验证问题的解决方法

更多相关阅读请进入《nodejs》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...