欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

node Buffer缓存区常见操作示例

程序员文章站 2022-06-24 13:07:18
本文实例讲述了node buffer缓存区常见操作。分享给大家供大家参考,具体如下: 创建buffer类 var buf=new buffer(10); va...

本文实例讲述了node buffer缓存区常见操作。分享给大家供大家参考,具体如下:

创建buffer类

var buf=new buffer(10);
var buf=new buffer([10,20,30,40]);
var buf=new buffer("www.baidu.com","utf-8");

写入缓存区

buf.write(string[,offset[,length]][encoding])
buf=new buffer(256);
len=buf.write("www.baidu.com")
console,log("写入字节数:"+len)

从缓存读取数据

buf.tostring([encoding[,start[,end]]])
buf=new buffer(26);
for(var i=0;i<26;i++;){
buf[i]=i+97;
}
console.log(buf.tostring('ascill'));
console.log(buf.tostring('ascill',0,5))
console.log(buf.tostring('utf-8',0,5))
console.log(buf.tostring('undefined',0,5))

转为json

buf.tojson()
var buf=new buffer('www.baidu.com');
var json=buf.tojson('buf')
console.log(json)

缓存合并

buffer.concat(list[,totallength]);
var buffer1=new buffer('百度搜索');
var buffer2=new buffer('www.baidu.com');
var buffer3=buffer.concat([buffer1,buffer2]);
console.log("buffer3内容"+buffer3.tostring())

缓存区比较

buf.compare(otherbuffer)
var buffer1=new buffer('abc');
var buffer2=new buffer('abcd');
var result=buffer1.compare(buffer2);
if(result<0){
console.log(buffer1+"在"+buffer2+"之前")
}else if(result==0){
console.log(buffer1+"等于"+buffer)
}else{
console.log(buffer1+"在"+buffer2+"之后")
}

拷贝缓存区

buf.copy(targetbuffer[,targetstart[,sourcestart[,sourcend]]])
var buffer1=new buffer('abc');
var buffer2=new buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content:"+buffer2.tostring())

缓存区裁剪

buf.slice([start[,end]])
var buffer1=new buffer('baidu')
var buffer2=buffer1.slice(0,2);
console.log("buffer2 content:"+buffer2.tostring());
buffer2 content:ba

缓存区长度

buf.length
var buffer=new buffer("www.baidu.com");
console.log("buffer length:"+buffer.length)
buffer length:13

希望本文所述对大家node.js程序设计有所帮助。