处理数据I/O之Buffer

一:Buffer对象的创建方式:

  (1):概述:Node.js中的Buffer缓冲区模块支持开发者在缓冲区结构中创建、读取、写入和操作二进制数据,该模块是全局性的。

  (2):通过Buffer构造函数:

    1:参数可以是,字节,数组,buffer对象,字符串。等

    

/*
使用构造函数在缓存区创建一个内存为8个字节的空间:
*/
try{
var size = 8;
var buf = new Buffer(size);
//传入数组方式创建Buffer实列
var buf_arry = new Buffer([5,10,15,20]);
//传入字符串和编码
var buf_str = new Buffer("hello","UTF-8");
}
catch(e)
{
    console.log(e);
}
输出:

D:\Program Files\nodejs\chapter>node Buffer构造函数.js
<Buffer 05 0a 0f 14>
(node:7456) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

 

  2:向缓存区写入内容:

  

/*
写入缓存区:buf.write(string,offset,length,encoding)
    string:写入的字符串
    offset:写入的位置,即索引
    length:长度.
*/
console.log('创建一个10字节的缓存区');
var buf = new Buffer(10);
console.log('缓存区的大小'+buf.length);
 var L = buf.write('a',0,1,'utf-8'); //write返回的内容为实际写入的大小
console.log("write的返回值"+L);
console.log("缓存的内容"+buf);
//在ascii编码表中字母a的十六进制数表示为61,
//占用一个字节,b表示为62,占用一个字节。
buf.write('b',1,1,'ascii');
输出:

D:\Program Files\nodejs\chapter>node 写入缓存区.js
创建一个10字节的缓存区
缓存区的大小10
write的返回值1
缓存的内容a
(node:2256) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

 3:读取缓存区内内容:

var buf = new Buffer(26); //创建一个26字节地内存对象
for(var i = 0;i<26;i++)
{
    buf[i] = i+97;
}
//以ascil编码输出:
console.log(buf.toString('ascii'));
//输出前五个字节
console.log(buf.toString('ascii',0,5));
//输出从索引5开始到10个字节
console.log(buf.toString('utf-8',5,15));
输出:

D:\Program Files\nodejs\chapter>node 读取缓存区.js
abcdefghijklmnopqrstuvwxyz
abcde
fghijklmno
(node:7416) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

4:拼接缓存区

/*
buf.concat(list[buf1,buf2,.....,totalLength])
totalLength用于指定合并后Buffer对象的总长度。
*/
var buf1 = new Buffer('会当凌绝顶');
var buf2 = new Buffer('一览众山小');
var buf4 = new Buffer(',');
//拼接缓冲区
var buf3 = Buffer.concat([buf1,buf4,buf2,],40);
console.log(buf3.length); //拼接后地长度
console.log(buf3.toString('utf-8'));
输出:

D:\Program Files\nodejs\chapter>node 拼接缓存区.js
40
会当凌绝顶,一览众山小
(node:852) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

5:使用buffer对象作为构造函数参数进行上述操作.

6:使用数组作为构造函数参数进行上述操作.

posted @ 2020-03-15 19:14  calm寻路人  阅读(448)  评论(0编辑  收藏  举报