Global中的
Nuffer
类(一个用于更好操作二进制数据的类)
我们在操作文件或者网络数据的时候,其实是在操作的就是二进制的数据流,
Node
为我们提供了一个更加方便的去操作这种数据流的类,他是一个全局的类
- 创建
Buffer
new Buffer(size); size[Number] 为这个对象分配一个大小,但是长度是固定的 不能更改
var str1 = 'miaov';
var bf1 = new Buffer(str1);
console.log(str1.length);//5
console.log(bf1.length);//5
var str2 = "我的";
var bf2 = new Buffer(str2);
console.log(str2.length);//2
console.log(bf2.length);//6
buf.write();写入(从Buffer对象中几位开始显示)
var str = 'miaov';
console.log(new Buffer(str));//<Buffer 00 00 00 00 00>
var bf = new Buffer(5);
bf.write(str);
console.log(bf);//<Buffer 6d 69 61 6f 76>
- 偏移量
var str = 'miaov';
console.log(new Buffer(str));//<Buffer 00 00 00 00 00>
var bf = new Buffer(5);
bf.write(str);
console.log(bf);//<Buffer 6d 69 61 6f 76>
偏移量
bf.write(str,1);
console.log(bf);//<Buffer 00 6d 69 61 6f>
bf.write(str,1,3);//<Buffer 00 6d 69 61 00>
console.log(bf)
var bf = new Buffer("miaov");
console.log(bf);//<Buffer 6d 69 61 6f 76>
console.log(bf.toString());//miaov
console.log(bf.toString('utf-8',1,3));//ia
var bf1 = new Buffer("测试");
console.log(bf1);//<Buffer e6 b5 8b e8 af 95>
console.log(bf1.toString('utf-8',1));//��试
console.log(bf.toJSON());//{ type: 'Buffer', data: [ 109, 105, 97, 111, 118 ] }
- 强弱引用
var bf1 = new Buffer("miaov");
console.log(bf1); //<Buffer 6d 69 61 6f 76>
var bf2 = bf1.slice( 2,4); //<Buffer 61 6f>
bf2[0] = 2;//强引用,改变引用bf1的值
console.log(bf2);//<Buffer 02 6f>
console.log(bf1);//<Buffer 6d 69 02 6f 76>
var bf1 = new Buffer("miaov");
console.log(bf1);//<Buffer 6d 69 61 6f 76>
var bf2 = new Buffer(5);
bf1.copy(bf2);//不会引起引用bf1的值改变
bf2[0] = 2;
console.log(bf2);//<Buffer 02 69 61 6f 76>
-
Buffer
的合并
var str1 = 'miaov';
var str2 = '妙味';
var list = [new Buffer(str1),new Buffer(str2)];
console.log(list);//[ <Buffer 6d 69 61 6f 76>, <Buffer e5 a6 99 e5 91 b3> ]
//Buffer.concat([],合并后的长度)
var bf = Buffer.concat(list,11);
console.log(bf);//<Buffer 6d 69 61 6f 76 e5 a6 99 e5 91 b3>
- 输出流打印的也是Buffer
process.stdout.write('请输入:');
process.stdin.resume();
process.stdin.on('data',function(para)
{
//<Buffer 0a>:就是回车换行
console.log('输入的内容是:' + para.toString());
console.log(para);
});
-----------------------打印内容-----------------------------
请输入:asd
输入的内容是:asd
<Buffer 61 73 64 0a>