http://nodejs.org/api/buffer.html
Pure JavaScript is Unicode friendly but not nice to binary data. When dealing with TCP streams or the file system, it's necessary to handle octet streams. Node has several strategies for manipulating, creating, and consuming octet streams.
Raw data is stored in instances of the Buffer
class. A Buffer
is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer
cannot be resized.
The Buffer
class is a global, making it very rare that one would need to ever require('buffer')
.
Converting between Buffers and JavaScript string objects requires an explicit encoding method. Here are the different string encodings.
'asicc','binary'等。
Creating a typed array from a Buffer
works with the following caveats:caveat:缺陷
The buffer's memory is copied, not shared.
The buffer's memory is interpreted as an array, not a byte array. That is,
new Uint32Array(new Buffer([1,2,3,4]))
creates a 4-elementUint32Array
with elements[1,2,3,4]
, not anUint32Array
with a single element[0x1020304]
or[0x4030201]
.
NOTE: Node.js v0.8 simply retained a reference to the buffer in array.buffer
instead of cloning it.
While more efficient, it introduces subtle incompatibilities with the typed arrays specification.ArrayBuffer#slice()
makes a copy of the slice while Buffer#slice()
creates a view.
new Buffer(str, [encoding])#
-
str
String - string to encode. -
encoding
String - encoding to use, Optional.
Allocates a new buffer containing the given str
. encoding
defaults to 'utf8'
.
new Buffer(size)#
-
size
Number
Allocates a new buffer of size
octets.
new Buffer(array)#
-
array
Array
Allocates a new buffer using an array
of octets.
> new Buffer([255,0,149]);
<Buffer ff 00 95>
>
如例4-24 所示的例子,我们用字符串来创建Buffer,它默认是UTF-8 编码的。如
果你没有指定编码格式,它就会认为是UTF-8 字符串。这并不意味着Buffer 会
把字符串补全成能够存下任意Unicode 字符的大小(盲目地为每个字符分配4 个字
节),而是说明它不会截断字符内容。在这个例子中,我们看到当输入的字符串是小
写字母时,无论采用的是哪种编码方式,Buffer 都使用同样的字节结构,因为每
个字母都落在同样的区间里。但是,当我们输入“é”字符时,无论是默认的UTF-8
还是我们显式指定为UTF-8,它都被编码成2 个字节大小。但是当我们指定编码为
ASCII 时,字符被截断成单个字节。
你还可以往已经存在的Buffer 上写入字符串。Buffer.write() 会把字符串写到
Buffer 指定的位置上。如果从Buffer 指定位置开始有足够空间的话,整个字符串
都会被写入。否则,字符串的尾部会被截断,好让其大小能放入Buffer。在这两
种情况下,Buffer.write() 都会返回一个数字,表示有多少字节被成功写入。对
于UTF-8 字符串来说,如果一个完整字符无法写入到Buffer 的话,就不会单独写
入该字符的某个字节。如在例4-25 中,因为Buffer 太小了,以至于无法写入一个
非ASCII 字符,所以它就是空的。
你还可以往已经存在的Buffer 上写入字符串。Buffer.write() 会把字符串写到Buffer 指定的位置上。如果从Buffer 指定位置开始有足够空间的话,整个字符串都会被写入。否则,字符串的尾部会被截断,好让其大小能放入Buffer。在这两种情况下,Buffer.write() 都会返回一个数字,表示有多少字节被成功写入。对于UTF-8 字符串来说,如果一个完整字符无法写入到Buffer 的话,就不会单独写入该字符的某个字节。如在例4-25 中,因为Buffer 太小了,以至于无法写入一个非ASCII 字符,所以它就是空的。