NodeJS3-2基础API----Buffer(缓冲器)
Buffer(缓冲器)
- Buffer是用于处理二进制数据流的
- 实例类似整数数组,大小固定(实例化之后,是多大就多大,不能进行变更)
- C++代码在V8 对外分配物理内存
- Buffer是全局变量,没必要使用require来引用
//常见一个规定长度,默认用0填充 console.log(Buffer.alloc(10)); console.log(Buffer.alloc(20)); // 用2填充 console.log(Buffer.alloc(5,2)); // 创建一个长度为 5、且未初始化的 Buffer。这个方法比调用 Buffer.alloc() 更快, // 但返回的 Buffer 实例可能包含旧数据,因此需要使用 fill() 或 write() 重写。 console.log(Buffer.allocUnsafe(5,2)); console.log(Buffer.from([1,2,3])); console.log(Buffer.from('test')); //指定编码 console.log(Buffer.from('test','base64'));
运行结果
静态的属性和方法(Buffer类本身的属性和方法)[常用的]
Buffer.byteLength & Buffer.isBuffer() & Buffer.concat()
// 实际占了几个字节 console.log(Buffer.byteLength('test')); //一个中文三个字节 console.log(Buffer.byteLength('测试')); console.log(Buffer.isBuffer({})); console.log(Buffer.isBuffer(Buffer.from([1,2,3]))); const buf1 = Buffer.from('This') const buf2 = Buffer.from(' is ') const buf3 = Buffer.from('a ') const buf4 = Buffer.from('test ') const buf5 = Buffer.from('!') const buf = Buffer.concat([buf1,buf2,buf3,buf4,buf5]) console.log(buf.toString());
运行结果:
实例的常用属性和方法(6种)
buf.length buf.toString() buf.fill()
buf.equals() buf.indexOf() buf.copy()
//1.buf.length const buf = Buffer.from('This is a test!') console.log(buf.length); //15 const buf2 = Buffer.alloc(10); const buf3 = Buffer.allocUnsafe(10); //默认不填充 buf2[0]=2 //下面证明,就算默认不填充,可是长度是根据你一开始创建的大小来控制,与填不填充内容无关 console.log(buf2.length); //10 console.log(buf3.length); //10 //2.buf.toString() console.log(buf.toString()); //默认utf-8 This is a test console.log(buf.toString('base64')); //VGhpcyBpcyBhIHRlc3Qh //3.buf.fill() alloc是自动填充0,但是可以用fill()来填充其他的值 const buf4 = Buffer.allocUnsafe(10) console.log(buf4); console.log(buf4.fill(10,2,6));//fill(像填充的内容,从哪里开始,从哪里结束) //4.buf.equals() 两个Buffer的内容是否相等 const buf5 = Buffer.from('test') const buf6 = Buffer.from('test') const buf7 = Buffer.from('test!') console.log(buf5.equals(buf6)); //true console.log(buf5.equals(buf7)); //false //5.buf.indexOf() buf5=test console.log(buf5.indexOf('s')); //找到就返回所在位置的index(从0开始) console.log(buf5.indexOf('a'));//找不到就返回-1 //6.buf.copy() const buf8 = Buffer.allocUnsafe(10).fill('*') const buf9 = Buffer.allocUnsafe(10).fill('!') //拷贝'buf8'中第 3-6字节数据到'buf9'第4个偏移量开始 buf8.copy(buf9,4,3,6) console.log(buf9.toString()); // !!!!***!!!
//乱码
const StringDecoder = require('string_decoder').StringDecoder
//自定义的decoder
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(b.toString());//乱码
}
for(let i =0 ;i<buf.length ; i+=5){
const b = Buffer.allocUnsafe(5)
buf.copy(b,0,i)
//用decoder来打印,决定打印的内容
console.log(decoder.write(b)); //没有乱码
}
//decoder并不会意识到自己处理中文(宽字节),