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

返回前面的内容

相关阅读 >>

node.js访问sql数据库的方法

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

nodejs怎么结束进程

前端用nodejs能做什么

浅谈nodejs如何进行多线程处理

windows环境下怎么安装nodejs

详解多个node版本下如何指定版本运行项目?

2021年8个值得收藏的nodejs项目

了解nodejs中的模块载入

一文快速了解nodejs中crypto模块的用法

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




打赏

取消

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

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

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

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

评论

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