Node API翻译 一 Buffer

每一个Node API 都会标识一个API稳定性,如下图:

image


Buffer#

Stability: 3 - Stable

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.

纯正的JS是对Unicode友好,却对字节数据不友好,而当处理TCP流或者文件系统时,必须处理二进制(8位为1字节)流。Node也有一些策略去操纵,创建,消费字节流。

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.

原始数据存储在Buffer类的实例中,一个Buffer类似于一个在对应的V8堆(the V8 heap)外部原始内存分配的int数组。Buffer创建后无法更改其大小。

The Buffer class is a global, making it very rare that one would need to ever require('buffer').

Buffer类是全局的,所以他是仅有几个不必使用require('buffer').引用的。

Converting between Buffers and JavaScript string objects requires an explicit encoding method. Here are the different string encodings.

在Buffers和JS String对象之间转换需要一个明确的编码方法。下面是string各个编码的不同。

  • 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.

  • 'ascii' -之对应7位的ASCII数据. 这个编码方法非常快,但是会去掉高位如果设置了他。(

    ASCII有7位,8位的区别,国人常见7位,上边说的即使你设置了8位也会被移出成7位

    7位范围:0000000~1111111,最小0,最大127,共128个

    8位范围:00000000~11111111,最小0,最大255,共256个

  • Note that when converting from string to buffer, this encoding converts a null character ('\0' or'\u0000') into 0x20 (character code of a space). If you want to convert a null character into 0x00, you should use 'utf8'.

  • 注意:当从string向buffer转换时,这个编码会把null字符(\0 or \u0000)转换成0x20(空格字符)。如果你想转换成对应的空字符,请用UTF-8编码

  • 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.

  • 'utf8' 是多字节编码的Unicode字符集,许多网页和文档都使用他。

  • 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.

  • 'ucs2' - Alias of 'utf16le'.

  • 'base64' - Base64 string encoding.

  • 'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.

  • 'hex' - Encode each byte as two hexadecimal characters.

A Buffer object can also be used with typed arrays. The buffer object is cloned to an ArrayBuffer that is used as the backing store for the typed array. The memory of the buffer and the ArrayBuffer is not shared.

一个 Buffer 对象也能被用作类型数组。buffer对象是一个ArrayBuffer 副本,为类型数组提供后备存储。buffer和ArrayBuffer 的内存并不共享

NOTE: Node.js v0.8 simply retained a reference to the buffer in array.buffer instead of cloning it.

注意:Node只简单的保留一个buffer引用来代替去克隆他

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.

Class: Buffer#

The Buffer class is a global type for dealing with binary data directly. It can be constructed in a variety of ways.

Buffer类是一个用来直接处理二进制数据的全局类型,他可以通过多种途径构造

new Buffer(size)#
  • size Number

Allocates a new buffer of size octets.

分配一个新的大小为Number的buffer

new Buffer(array)#
  • array Array

Allocates a new buffer using an array of octets.

分配一个新的字节array的buffer

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'.

分配一个新的buffer带有指定的编码,默认是utf-8

 

Class Method: Buffer.isEncoding(encoding)#
  • encoding String The encoding string to test

Returns true if the encoding is a valid encoding argument, or false otherwise.

如果encoding有效则返回true,否则false

buf.write(string, [offset], [length], [encoding])#

  • string String - data to be written to buffer
  • offset Number, Optional, Default: 0
  • length Number, Optional, Default: buffer.length - offset
  • encoding String, Optional, Default: 'utf8'

Writes string to the buffer at offset using the given encoding. offset defaults to 0, encoding defaults to'utf8'. length is the number of bytes to write. Returns number of octets written. If buffer did not contain enough space to fit the entire string, it will write a partial amount of the string. length defaults tobuffer.length - offset. The method will not write partial characters.

把一个string从offset开始用给定的编码写入到buffer中,offset默认是0,encoding默认是utf-8。length代表写入多少个字节。返回值是写入了多少字节.如果buffer没有足够的空间容纳写入的字符串,这个方法会写入字符串的一部分,写入部分长度默认为原始buffer的长度-起始长度。该方法将不会写入部分字符(ps:比如一个utf-8的汉字可能会占用3个字节,也可能4个字节,该方法不会写入一半字符。)

 

The number of characters written (which may be different than the number of bytes written) is set inBuffer._charsWritten and will be overwritten the next time buf.write() is called.

写入的字符数(可能和写入的字节数不同,因为有些字符会占用2个字节)被写入到Buffer._charsWritten属性中,他会在下次buf.write()调用前重写

buf.toString([encoding], [start], [end])#

  • encoding String, Optional, Default: 'utf8'
  • start Number, Optional, Default: 0
  • end Number, Optional, Default: buffer.length

Decodes and returns a string from buffer data encoded with encoding (defaults to 'utf8') beginning at start(defaults to 0) and ending at end (defaults to buffer.length).

解码并已string形式返回一个用encoding(默认utf-8)编码的buffer数据,从start开始到ending结束。

buf.toJSON()#

Returns a JSON-representation of the Buffer instance, which is identical to the output for JSON Arrays.JSON.stringify implicitly calls this function when stringifying a Buffer instance.

返回一个BUffer实例的Json对象,等同于输出JSON数组。JSON.stringify在串化Buffer实例时也调用这个方法。

Example:

   1: var buf = new Buffer('test');
   2: var json = JSON.stringify(buf);
   3:  
   4: console.log(json);
   5: // '[116,101,115,116]'
   6:  
   7: var copy = new Buffer(JSON.parse(json));
   8:  
   9: console.log(copy);
  10: // <Buffer 74 65 73 74>
ps:可以看到JSON.stringify 和该方法的结果是一样的

buf[index]#

Get and set the octet at index. The values refer to individual bytes, so the legal range is between 0x00 and0xFF hex or 0 and 255.

Example: copy an ASCII string into a buffer, one byte at a time:

获取或设置位于index的字节。由于返回的是独立的字节值,因此他的有效的范围是0x000xFF 16进制 或 0 and 255.

Example: copy an ASCII string into a buffer, one byte at a time:

一次复制一个ASCII字节到buffer中

   1: str = "node.js";
   2: buf = new Buffer(str.length);
   3:  
   4: for (var i = 0; i < str.length ; i++) {
   5:   buf[i] = str.charCodeAt(i);
   6: }
   7:  
   8: console.log(buf);
   9:  
  10: // node.js

Class Method: Buffer.isBuffer(obj)#

  • obj Object
  • Return: Boolean

Tests if obj is a Buffer.

测试obj是否是一个buffer

Class Method: Buffer.byteLength(string, [encoding])#

  • string String
  • encoding String, Optional, Default: 'utf8'
  • Return: Number

Gives the actual byte length of a string. encoding defaults to 'utf8'. This is not the same asString.prototype.length since that returns the number of characters in a string.

给出一个string的实际字节长度。encoding默认为utf-8.这个方法与String.prototype.length不同,因为后者返回字符长度

Example:

str = '\u00bd + \u00bc = \u00be';

console.log(str + ": " + str.length + " characters, " +
  Buffer.byteLength(str, 'utf8') + " bytes");

// ½ + ¼ = ¾: 9 characters, 12 bytes

Class Method: Buffer.concat(list, [totalLength])

类方法(静态方法)

  • list Array List of Buffer objects to concat  用来连接的Buffer对象数组
  • totalLength Number Total length of the buffers when concatenated

Returns a buffer which is the result of concatenating all the buffers in the list together.

返回一个把多个buffer 列表链接到一起的buffer

If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.

如果列表中没有元素,或者他的totalLength是0,该方法会返回一个长度为0的buffer

If the list has exactly one item, then the first item of the list is returned.

如果列表恰好只有一个元素,那么会返回列表的第一个元素

If the list has more than one item, then a new Buffer is created.

如果列表中含有多余1个元素,则会创建一个新的Buffer。

If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.

如果totalLength没有提供,该参数会从列表中读取。然而,这样会增加一次读取长度循环,所以还是传递一个长度比较快。

buf.length#

  • Number

The size of the buffer in bytes. Note that this is not necessarily the size of the contents. lengthrefers to the amount of memory allocated for the buffer object. It does not change when the contents of the buffer are changed.

buffer的字节大小,请注意这个和内容占的大小无关,而是buffer对象分配空间的大小。所以这个大小是恒定不变的。

   1: buf = new Buffer(1234);
   2:  
   3: console.log(buf.length);//4
   4: buf.write("some string", 0, "ascii");
   5: console.log(buf.length);//4
   6:  

buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])#

  • targetBuffer Buffer object - Buffer to copy into
  • targetStart Number, Optional, Default: 0
  • sourceStart Number, Optional, Default: 0
  • sourceEnd Number, Optional, Default: buffer.length

Does copy between buffers. The source and target regions can be overlapped.targetStart and sourceStart default to 0. sourceEnd defaults tobuffer.length.

在buffer对象间复制,原和目标区域可以被重叠。targetStartsourceStart 默认是0,。sourceEnd 默认是源的长度

All values passed that are undefined/NaN or are out of bounds are set equal to their respective defaults.

所有传进来的值如果是undefined/NaN 或者超出范围会被设置成他们各自的默认值。

Example: build two Buffers, then copy buf1 from byte 16 through byte 19 intobuf2, starting at the 8th byte in buf2.
创建2个Buffer实例,然后将buf1中第16字节到第19字节间的信息复制到buf2中,并使在buf2中新的字符串首字符位于第8字节:

   1: buf1 = new Buffer(26);
   2: buf2 = new Buffer(26);
   4: for (var i = 0 ; i < 26 ; i++) {
   5:   buf1[i] = i + 97; // 97 is ASCII a
   6:   buf2[i] = 33; // ASCII !
   7: }
   8:  
   9: buf1.copy(buf2, 8, 16, 20);
  10: console.log(buf2.toString('ascii', 0, 25));

buf.slice([start], [end])#

  • start Number, Optional, Default: 0
  • end Number, Optional, Default: buffer.length

Returns a new buffer which references the same memory as the old, but offset and cropped by the start(defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.

返回一个新的buffer,他和老的buffer引用相同的内存。通过start和end进行裁剪。负的索引则从buffer末尾开始。

Modifying the new buffer slice will modify memory in the original buffer!

特别注意:通过修改新的Buffer切片(slice)中的内容同样会修改存储在原Buffer中的信息!(反之亦然,通过索引修改)

Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte from the original Buffer.

例如:建立一个ASCII码型的字母表,再建立一个切片,并在原Buffer中修改一个字节:

   1: var buf1 = new Buffer(26);
   2:  
   3: for (var i = 0 ; i < 26 ; i++) {
   4:   buf1[i] = i + 97; // 97 is ASCII a
   5: }
   6:  
   7: var buf2 = buf1.slice(0, 3);
   8: console.log(buf2.toString('ascii', 0, buf2.length));
   9: buf1[0] = 33;
  10: console.log(buf2.toString('ascii', 0, buf2.length));
  11:  
  12: // abc
  13: // !bc
buf.readUInt8(offset, [noAssert])#
  • offset Number
  • noAssert Boolean, Optional, Default: false
  • Return: Number

Reads an unsigned 8 bit integer from the buffer at the specified offset.

读取指定的偏移量的buff中的8位无符号整数

Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

设置noAssert 为true去跳过验证offset。这意味着offset可以超过buffer边界。默认值是false

Example:

   1: var buf = new Buffer(4);
   2:  
   3: buf[0] = 0x3;
   4: buf[1] = 0x4;
   5: buf[2] = 0x23;
   6: buf[3] = 0x42;
   7:  
   8: for (ii = 0; ii < buf.length; ii++) {
   9:   console.log(buf.readUInt8(ii));
  10: }
 

buf.readUInt16LE(offset, [noAssert])#

buf.readUInt16BE(offset, [noAssert])#

buf.readUInt32LE(offset, [noAssert])#

buf.readUInt32BE(offset, [noAssert])

buf.readInt8(offset, [noAssert])

buf.readInt16LE(offset, [noAssert])#

buf.readInt16BE(offset, [noAssert])

buf.readInt16LE(offset, [noAssert])#

buf.readInt16BE(offset, [noAssert])

buf.readFloatLE(offset, [noAssert])#

buf.readFloatBE(offset, [noAssert])

buf.readDoubleLE(offset, [noAssert])#

buf.readDoubleBE(offset, [noAssert])

同readUint8

buf.writeUInt8(value, offset, [noAssert])#

  • value Number
  • offset Number
  • noAssert Boolean, Optional, Default: false

Writes value to the buffer at the specified offset. Note, value must be a valid unsigned 8 bit integer.

Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

Example:

   1: var buf = new Buffer(4);
   2: buf.writeUInt8(0x3, 0);
   3: buf.writeUInt8(0x4, 1);
   4: buf.writeUInt8(0x23, 2);
   5: buf.writeUInt8(0x42, 3);
   6:  
   7: console.log(buf);

buf.writeUInt16LE(value, offset, [noAssert])#

buf.writeUInt16BE(value, offset, [noAssert])

buf.writeUInt32LE(value, offset, [noAssert])#

buf.writeUInt32BE(value, offset, [noAssert])

buf.writeInt8(value, offset, [noAssert])

buf.writeInt16LE(value, offset, [noAssert])#

buf.writeInt16BE(value, offset, [noAssert])

buf.writeInt16LE(value, offset, [noAssert])#

buf.writeInt16BE(value, offset, [noAssert])

buf.writeFloatLE(value, offset, [noAssert])#

buf.writeFloatBE(value, offset, [noAssert])

buf.writeDoubleLE(value, offset, [noAssert])#

buf.writeDoubleBE(value, offset, [noAssert])

同buf.writeUInt8

buf.fill(value, [offset], [end])#

  • value
  • offset Number, Optional
  • end Number, Optional

Fills the buffer with the specified value. If the offset (defaults to 0) and end (defaults tobuffer.length) are not given it will fill the entire buffer.

用指定的值填充buffer。如果offset和end没有给出则会填充整个buffer

var b = new Buffer(50);
b.fill("h");
image

buffer.INSPECT_MAX_BYTES#

  • Number, Default: 50

How many bytes will be returned when buffer.inspect() is called. This can be overridden by user modules.

buffer.inspect()被调用时将有多少字符会被返回。该属性可以被用户重写。

Note that this is a property on the buffer module returned by require('buffer'), not on the Buffer global, or a buffer instance.

注意:这是一个buffer模块的属性,必须引用require('buffer'), 不能在全局Buffer或者实例上调用

Class: SlowBuffer#

This class is primarily for internal use. JavaScript programs should use Buffer instead of using SlowBuffer.

这个类主要是内部使用的。JS程序应该使用Buffer来代替SlowBuffer。

In order to avoid the overhead of allocating many C++ Buffer objects for small blocks of memory in the lifetime of a server, Node allocates memory in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it will be backed by a parent SlowBuffer object. If it is larger than this, then Node will allocate a SlowBuffer slab for it directly.

为了避免在服务器生命周期中给一些小块内存分配许多C++ Buffer对象的开销,Node只申请8KB大小的内存区域。如果一个buffer小于这个大小,则会返回一个SlowBuffer对象。如果大于这个大小,则会直接申请一个SlowBuffer堆。

posted @ 2013-04-27 17:11  mylhei  阅读(702)  评论(0编辑  收藏  举报