本文实例讲述了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.lengthvar buffer=new Buffer("www.baidu.com");console.log("buffer length:"+buffer.length)buffer length:13
希望本文所述对大家node.js程序设计有所帮助。
新闻热点
疑难解答