Buffer.byteLength

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

每个中文是3个字节

Buffer.isBuffer

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

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());

实例的常见用法

buf.length

const buf = Buffer.from('你好');
console.log(buf.length); const buf2 = Buffer.alloc(10);
buf2[0] = 2;
console.log(buf2.length);

buf.toString()

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

buf.fill()

const buf3 = Buffer.allocUnsafe(10);
console.log(buf3);
console.log(buf3.fill(10,2,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));

比较两个内容是否一样:

buf.indexOf()

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

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());
}

输出是乱码:

输出存在乱码

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));
}
05-23 06:34