NodeJS基础入门-Buffer

Buffer.byteLength

console.log(Buffer.byteLength('test'));
console.log(Buffer.byteLength('我是C语言爱好者'));

4
22

每个中文是3个字节

Buffer.isBuffer

console.log(Buffer.isBuffer({}));
console.log(Buffer.isBuffer(Buffer.from([1,2,3])));

false #第一个不是Buffer
true #第二个是Buffer

Buffer.concat()

const buf1 = Buffer.from('This ');
const buf2 = Buffer.from('is ');
const buf3 = Buffer.from('a ');
const buf4 = Buffer.from('book ');

console.log(Buffer.concat([buf1, buf2, buf3, buf4]).toString());

This is a book

实例的常见用法

buf.length

const buf = Buffer.from('你好');
console.log(buf.length);

const buf2 = Buffer.alloc(10);
buf2[0] = 2;
console.log(buf2.length);

6 # 中文字符3个字节
10 # 固定分配10个长度单位

buf.toString()

console.log(buf.toString());
console.log(buf.toString('base64'));

你好 #默认UTF-8
5L2g5aW9 #设置为base64

buf.fill()

const buf3 = Buffer.allocUnsafe(10);
console.log(buf3);
console.log(buf3.fill(10,2,6));

<Buffer 00 00 00 00 00 00 00 00 48 c1>
<Buffer 00 00 0a 0a 0a 0a 00 00 48 c1> #填入10,十六进制0x0a,在buf3[2]到buf[6]的填入

buf.equals()

const buf = Buffer.from('test');
const buf2 = Buffer.from('test');
const buf3 = Buffer.from('test!');
console.log(buf.equals(buf2));
console.log(buf.equals(buf3));                          

比较两个内容是否一样:

true
false

buf.indexOf()

const buf = Buffer.from('test');
console.log(buf.indexOf('es'));
console.log(buf.indexOf('esa'));

1 #从buf[1]找到
-1 # 没有找到

Buffer乱码问题的解决

const buf = Buffer.from('中文字符串!');


for (let i = 0; i < buf.length; i += 5) {
  const b = Buffer.allocUnsafe(5);
  buf.copy(b, 0, i);
  console.log(b.toString());
}

输出是乱码:

中�
�字�
��串
!s=

输出存在乱码

const StringDecoder = require('string_decoder').StringDecoder;
const decoder = new StringDecoder('utf8');

const buf = Buffer.from('中文字符串!');
for (let i = 0; i < buf.length; i += 5) {
  const b = Buffer.allocUnsafe(5);
  buf.copy(b, 0, i); 
  console.log(decoder.write(b));
}


文字
符串
!9�
还是存在乱码,不知道什么原因?

posted @ 2018-12-10 11:04  cicarius  阅读(163)  评论(0编辑  收藏  举报