node 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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/0b38bd8bd1fd1fac685c2beb7457a0a2.html