Buffer

177 阅读1分钟

Node.js中,定义了一个Buffer类,该类用来创建一个专门存放二进制数据的缓存区. Buffer类在全局作用域中,因此不需要使用require('buffer')

1.创建

// 创建长度为10的以零填充的缓冲区
const buf1 = Buffer.alloc(10);
console.log(buf1);
// 创建长度为10的缓冲区,使用值为 `1`的字节填充.
const buf2 = Buffer.alloc(10, 1);
console.log(buf2);
/ 创建包含字节[1,2,3]的缓冲区
const buf4 = Buffer.from([1, 2, 3]);
console.log(buf4);

2.转换

// 当在Buffer和字符串之间进行转换时,可以指定字符编码,如果未指定字符编码,则默认使用UTF-8
const buf = Buffer.from('hello world', 'utf8');
console.log(`输出buf${buf}`);
// buffer转字符串
console.log(buf.toString())
// buffer转json
const buf6 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
console.log(buf.toJSON())

3.合并

  • Buffer.concat([buf1,buf2], totalLength) totalLength不是必须的,如果不提供的话会为了计算totalLength会多遍历一遍
const concat1 = Buffer.from('this is a ');
const concat2 = Buffer.from('book');
const concat3 = Buffer.concat([concat1, concat2], concat1.length + concat2.length);
console.log(concat3.toString());

4.清空

// 清空buffer数据最快的办法是buffer.fill(0)
const tempBuf = Buffer.alloc(10,1);
console.log(tempBuf);
console.log(tempBuf.fill(0));