本文實(shí)例講述了Node.js Buffer模塊功能及常用方法。分享給大家供大家參考,具體如下:
Buffer模塊
alloc()方法
alloc(size,fill,encoding)可以分配一個(gè)大小為 size 字節(jié)的新建的 Buffer,size默認(rèn)為0
var buf = Buffer.alloc(10);
參數(shù)fill為填充的數(shù)據(jù),只要指定了fill就會(huì)調(diào)用Buffer.fill(fill) 初始化這個(gè)Buffer對(duì)象
var buf = Buffer.alloc(10,0xff);//可以為十六進(jìn)制的數(shù)據(jù)
allocUnsafe()方法
Unsafe(size)顧名思義就是不安全的方法,因?yàn)橐赃@種方式創(chuàng)建的 Buffer 實(shí)例的底層內(nèi)存是未初始化的。甚至可能包含到敏感數(shù)據(jù),所以通過(guò)fill()方法幫助初始化
buf = Buffer.allocUnsafe(10);buf.fill(0);
allocUnsafeSlow()方法
allocUnsafeSlow()就是不從buffer緩沖區(qū)里分配,直接從操作系統(tǒng)分配,Slow指的是沒(méi)有從緩沖池里高效分配
buf = Buffer.allocUnsafeSlow(10);
from()方法
from()方法可以分配一個(gè)buffer對(duì)象,用來(lái)存放這個(gè)字符串的二進(jìn)制對(duì)象,因此Buffer的內(nèi)容可以通過(guò)[]進(jìn)行訪問(wèn)
buf = Buffer.from("HelloWorld!");//from(array)console.log(buf);buf = Buffer.from([123,22,24,36]);console.log(buf);//重建一個(gè)buffer,把原來(lái)Buffer的數(shù)據(jù)拷貝給新的bufferbuf2 = Buffer.from(buf);console.log(buf2);//buf[index] index取值范圍[0,len-1]console.log(buf[0],buf[1]);大尾與小尾形式寫入存儲(chǔ)
writeInt32BE(value,offset)第一個(gè)參數(shù)為寫入的數(shù)據(jù),第二個(gè)參數(shù)從哪個(gè)位置開(kāi)始寫入 ,表示其以大尾(大端)形式寫入writeInt32LE(value,offset)以小尾(小端)的形式寫入數(shù)據(jù)
//以大尾的形式存放,4個(gè)字節(jié)的整數(shù)buf.writeInt32BE(65535,0);console.log(buf);//以小尾的方式寫入buf.writeInt32LE(65535,0);console.log(buf);
大尾小尾形式讀取數(shù)據(jù)
readInt32LE(offset)是指以小尾整型形式讀取數(shù)據(jù)readFloatLE(offset)是指以小尾浮點(diǎn)形式讀取數(shù)據(jù)
var value = buf.readInt32LE(0);console.log(value);buf.writeFloatLE(3.16,0);console.log(buf.readFloatLE(0));
讀取數(shù)據(jù)的各種方式
//讀取長(zhǎng)度var len = Buffer.byteLength("HelloWorld");console.log(len);buf = Buffer.alloc(4*4);buf.writeInt32LE(65535,0);buf.writeInt32LE(65535,4);buf.writeInt32LE(65535,8);buf.writeInt32LE(65535,12);console.log(buf);buf.swap32();console.log(buf);//用高位的方式讀取console.log(buf.readInt32BE(0));console.log(buf.readInt32BE(4));console.log(buf.readInt32BE(8));console.log(buf.readInt32BE(12));for (var i of buf.values()) { console.log(i);}轉(zhuǎn)換
//以二進(jìn)制方式轉(zhuǎn)為字符串console.log(buf.toString('hex'));console.log(buf.toJSON());buf.fill('A');console.log(buf);console.log(buf.toString('utf8'));
新聞熱點(diǎn)
疑難解答
圖片精選