用的频率高,所以直接挂到了global下面,像console一样使用!
一、什么是buffer
- Buffer是用于处理二进制数据流的
- 实例类似整数数组,大小固定(buffer不能像数组一样扩充,在创建里确定,无法调整)
- C++代码在V8堆外分配物理内存(node是用C++写的)
二、具体的方法学习
// 创建一个长度为 10、且用零填充的 Buffer。result:<Buffer 00 00 00 00 00 00 00 00 00 00>
console.log(Buffer.alloc(10));
// 创建一个长度20,填充0的Buffer
console.log(Buffer.alloc(20));
// 创建一个长度为 10,填充1的result:<Buffer 01 01 01 01 01 01 01 01 01 01>
console.log(Buffer.alloc(10, 1));
// 创建一个长度为 10、且未初始化的 Buffer。
// 这个方法比调用 Buffer.alloc() 更快,
// 但返回的 Buffer 实例可能包含旧数据,
// 因此需要使用 fill() 或 write() 重写
console.log(Buffer.allocUnsafe(10));
// 创建一个包含 [0x1, 0x2, 0x3] 的 Buffer。result:<Buffer 01 02 03>
console.log(Buffer.from([1, 2, 3]));
// -------------------------------------------------------------------------------------------
// 创建一个包含 UTF-8(默认) 字节 [0x74, 0xc3, 0xa9, 0x73, 0x74] 的 Buffer。
console.log(Buffer.from('test'));
// 创建一个包含 Latin-1 字节 [0x74, 0xe9, 0x73, 0x74] 的 Buffer。
console.log(Buffer.from('test', 'latin1'));
console.log(Buffer.from('test', 'base64'));
// -------------------------------------------------------------------------------------------
console.log("Buffer字节长度(英文):" + Buffer.byteLength('hello world'));
console.log("Buffer字节长度(中文):" + Buffer.byteLength('你好世界'));
// -------------------------------------------------------------------------------------------
console.log("是否是Buffer对象:" + Buffer.isBuffer("123"));
console.log("是否是Buffer对象:" + Buffer.isBuffer(Buffer.from([1, 2, 3])));
// -------------------------------------------------------------------------------------------
const buf1 = Buffer.from('hello ');
const buf2 = Buffer.from('world');
var buf = Buffer.concat([buf1, buf2]);
console.log("拼接结果:" + buf.toString());
// -------------------------------------------------------------------------------------------
console.log("Buffer.length: " + Buffer.from("this is a prity girl!").length);
var testLen1 = Buffer.alloc(12);
testLen1[1] = 3;
console.log("申请空间的大小: " + testLen1.length);
console.log("字符的base64: " + testLen1.toString("base64"));
// -------------------------------------------------------------------------------------------
var buf3 = Buffer.allocUnsafe(10);
console.log(buf3);
// 将10填充到,2~4的位置
console.log(buf3.fill(10, 2, 4));
// -------------------------------------------------------------------------------------------
const buf4 = Buffer.from("hello");
const buf5 = Buffer.from("hello");
const buf6 = Buffer.from("hello1");
console.log(buf4.equals(buf5));
console.log(buf4.equals(buf6));
// -------------------------------------------------------------------------------------------
const StringDecoder = require('string_decoder').StringDecoder;
const decoder = new StringDecoder('utf8');
const buf7 = Buffer.from('中文字符串哇吐露 !');
console.log(buf7.length);
for (let i = 0; i < buf7.length; i += 5) {
const b = Buffer.allocUnsafe(5);
buf7.copy(b, 0, i);
// console.log(b.toString());
console.log(decoder.write(b));
}