您的位置:首页 > Web前端 > Node.js

nodejs(三)Buffer module & Byte Order

2013-08-23 23:38 197 查看
一。目录

➤UnderstandingwhyyouneedbuffersinNode

➤Creatingabufferfromastring

➤Convertingabuffertoastring

➤Manipulatingthebytesinabuffer

➤Slicingandcopyingabuffer

二。UnderstandingwhyyouneedbuffersinNode

 JavaScriptisgoodathandlingstrings,butbecauseitwasinitiallydesignedtomanipulateHTMLdocuments,itisnotverygoodat

handlingbinarydata.JavaScriptdoesn’thaveabytetype—itjusthasnumbers—orstructuredtypes,orevenbytearrays:Itjust

hasstrings.  

  BecauseNodeisbasedonJavaScript,NodecanhandletextprotocolslikeHTTP,butyoucanalsouseittotalktodatabases,

manipulateimages,andhandlefileuploads.Asyoucanimagine,doingthisusingonlystringsisverydifficult.Intheearlydays,

Nodehandledbinarydatabyencodingeachbyteinsideatextcharacter,butthatprovedtobewasteful,slow,unreliable,andhard

tomanipulate.

  Tomakethesetypesofbinary-handlingtaskseasier,Nodeincludesabinarybufferimplementation,whichisexposedasaJavaScript

APIundertheBufferpseudo-class.Abufferlengthisspecifiedinbytes,andyoucanrandomlysetandgetbytesfromabuffer.

  AnotherthingthatisspecialaboutthisbufferclassisthatthememorywherethedatasitsisallocatedoutsideoftheJavaScriptVM

memoryheap.Thismeansthattheseobjectswillnotbemovedaroundbythegarbage-collectionalgorithm:Itwillsitinthispermanent

memoryaddresswithoutchanging,whichsavesCPUcyclesthatwouldbewastedmakingmemorycopiesofthebuffercontents.

三。GETTINGANDSETTINGBYTESINABUFFER

  Afteryoucreateorreceiveabuffer,youmightwanttoinspectandchangeitscontents.Youcanaccessthebytevalueonany

positionofabufferbyusingthe[]operatorlikethis:

varbuf=newBuffer('mybuffercontent');
//accessingthe10thpositionofbuf
console.log(buf[10]);//->99

  //Youcanalsomanipulatethecontentofanyposition:
  buf[20]=125;//setthe21thbyteto125



四。注意

NOTEWhenyoucreateaninitializedbuffer,keepinmindthatitwillcontainrandombytes,notzeros.

varbuf=newBuffer(1024);
console.log(buf[100]);//->5(somerandomnumber)


  

NOTEIncertaincases,somebufferoperationswillnotyieldanerror.Forinstance:

➤Ifyousetanypositionofthebuffertoanumbergreaterthan255,thatpositionwillbeassignedthe256modulovalue.

➤Ifyouassignthenumber256toabufferposition,youwillactuallybeassigningthevalue0.

➤Ifyouassignafractionalnumberlike100.7toabufferposition,thebufferpositionwillstoretheintegerpart—100inthiscase.

➤Ifyoutrytoassignapositionthatisoutofbounds,theassignmentwillfailandthebufferwillremainunaltered.

五。字节序

  又称端序,尾序(英语:ByteOrder,orEndianness)。现代的计算机系统一般采用字节(8bitByte)作为逻辑寻址单位。当物理单位的长度大于

1个字节时,就要区分字节顺序。典型的情况是整数在内存中的存放方式和网络传输的传输顺序。目前在各种体系的计算机中通常采用的字节存储机制主要

有两种:big-edian和little-endian。





六。字节序示例

varb=newBuffer('123456789');
console.log(b.length);//9
console.log(b);          //<Buffer313233343536373839>

varb2=newBuffer(4);
b2.writeInt32LE(123456789,0);
console.log(b2.length);      //4
console.log(b2);          //<Bufferb5e53907>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: