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:
//Youcanalsomanipulatethecontentofanyposition:
buf[20]=125;//setthe21thbyteto125
四。注意
NOTEWhenyoucreateaninitializedbuffer,keepinmindthatitwillcontainrandombytes,notzeros.
NOTEIncertaincases,somebufferoperationswillnotyieldanerror.Forinstance:
➤Ifyousetanypositionofthebuffertoanumbergreaterthan255,thatpositionwillbeassignedthe256modulovalue.
➤Ifyouassignthenumber256toabufferposition,youwillactuallybeassigningthevalue0.
➤Ifyouassignafractionalnumberlike100.7toabufferposition,thebufferpositionwillstoretheintegerpart—100inthiscase.
➤Ifyoutrytoassignapositionthatisoutofbounds,theassignmentwillfailandthebufferwillremainunaltered.
五。字节序
又称端序,尾序(英语:ByteOrder,orEndianness)。现代的计算机系统一般采用字节(8bitByte)作为逻辑寻址单位。当物理单位的长度大于
1个字节时,就要区分字节顺序。典型的情况是整数在内存中的存放方式和网络传输的传输顺序。目前在各种体系的计算机中通常采用的字节存储机制主要
有两种:big-edian和little-endian。
六。字节序示例
➤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>
相关文章推荐
- java之HeapByteBuffer&DirectByteBuffer以及回收DirectByteBuffer
- java之HeapByteBuffer&DirectByteBuffer以及回收DirectByteBuffer
- JDK ByteBuffer & MINA IoBuffer 总结 .
- java之HeapByteBuffer&DirectByteBuffer以及回收DirectByteBuffer
- NodeJS:cannot find module 'socket.io' | nmp全局安装 modules 后在应用中 require 不到的解决方案
- DirectByteBuffer内存申请与释放 && 可能会导致内存泄露的原因
- <Java>一个类bytebuffer使用
- JDK ByteBuffer & MINA IoBuffer 总结
- Host Byte Order & Network Byte Order
- JDK ByteBuffer & MINA IoBuffer 总结
- nodeJs启动的时候:Error: Cannot find module '../build/Release/bson'的解决办法
- Java&nbsp;NIO&nbsp;学习&nbsp;ByteBuffer,FileCha…
- nodejs报错:Cannot find module 'ejs'
- nodejs中exports与module.exports的区别详细介绍
- 解决UnicodeDecodeError: 'ascii' code can't decode byte 0xef in position
- fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'ARM
- 黑马程序员_毕向东Java基础_集合(1)String&StringBuffer&StringBuilder&基本数据类型包装类
- [Python]attributeError:'module' object has no attribute 'dump'
- nodejs中export与module.exports
- 用了整整一个晚上,就因为byte & int