处理数据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.

猜你喜欢

转载自www.cnblogs.com/1314bjwg/p/12499442.html