Latest web development tutorials

Node.js Buffer (buffer)

JavaScript language itself only string data types, no binary data type.

But when dealing with streams like TCP stream or file, you must use the binary data. Therefore, in Node.js, the definition of a Buffer class that is used to create a specialized storage buffer binary data.

In the Node.js, Buffer class is released together with the Node kernel core library. Buffer Node.js library brings a raw data storage method allows Node.js handle binary data, whenever you need to handle I / O operations to move data Node.js when it is possible to use Buffer library . The original data stored in the instance Buffer class. A Buffer is similar to an array of integers, but it corresponds to a raw memory outside the V8 heap.


Create Buffer class

Node Buffer class can be created in several ways.

method 1

Create instance a length of 10 bytes Buffer:

var buf = new Buffer(10);

Method 2

Through a given array creation Buffer Example:

var buf = new Buffer([10, 20, 30, 40, 50]);

Method 3

Create Buffer instance by a string:

var buf = new Buffer("www.w3big.com", "utf-8");

utf-8 is the default encoding, in addition it also supports the following encodings: "ascii", "utf8", "utf16le", "ucs2", "base64" and "hex".


Write buffer

grammar

Node write buffer syntax is as follows:

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

parameter

Parameters are described below:

  • string - the string buffer is written.

  • offset - the index buffer to start writing, the default is 0.

  • length - the number of bytes written, by default buffer.length

  • encoding - the encoding used.The default is 'utf8'.

return value

Returns the size of the actual writing. If the buffer space, the only portion of the string is written.

Examples

buf = new Buffer(256);
len = buf.write("www.w3big.com");

console.log("写入字节数 : "+  len);

Implementation of the above code, the output is:

$node main.js
写入字节数 : 14

Reads data from the buffer

grammar

Node read buffer data syntax is as follows:

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

parameter

Parameters are described below:

  • encoding - the encoding used.The default is 'utf8'.

  • start - start reading index position specified, the default is 0.

  • end - the end position, the default is the end of the buffer.

return value

Decoding buffer data and returns a string using the specified encoding.

Examples

buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
  buf[i] = i + 97;
}

console.log( buf.toString('ascii'));       // 输出: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5));   // 输出: abcde
console.log( buf.toString('utf8',0,5));    // 输出: abcde
console.log( buf.toString(undefined,0,5)); // 使用 'utf8' 编码, 并输出: abcde

Implementation of the above code, the output is:

$ node main.js
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde

Buffer will be converted to a JSON object

grammar

The Node Buffer into JSON object function syntax is as follows:

buf.toJSON()

return value

Returns JSON object.

Examples

var buf = new Buffer('www.w3big.com');
var json = buf.toJSON(buf);

console.log(json);

Implementation of the above code, the output is:

[ 119, 119, 119, 46, 114, 117, 110, 111, 111, 98, 46, 99, 111, 109 ]

Buffer Merge

grammar

Node buffer combined syntax is as follows:

Buffer.concat(list[, totalLength])

parameter

Parameters are described below:

  • list - an array of objects for Buffer combined list.

  • totalLength - after a specified total combined length of the Buffer object.

return value

Return multiple members of a merged new Buffer object.

Examples

var buffer1 = new Buffer('本教程 ');
var buffer2 = new Buffer('www.w3big.com');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 内容: " + buffer3.toString());

Implementation of the above code, the output is:

buffer3 内容: 本教程 www.w3big.com

Comparison buffer

grammar

Node Buffer compare function syntax is as follows, the method introduced in Node.js v0.12.2 version:

buf.compare(otherBuffer);

parameter

Parameters are described below:

  • otherBuffer - compared with bufBuffer objects to another object.

return value

It returns a number that representsbuf before otherBuffer,or after the same.

Examples

var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('ABCD');
var result = buffer1.compare(buffer2);

if(result < 0) {
   console.log(buffer1 + " 在 " + buffer2 + "之前");
}else if(result == 0){
   console.log(buffer1 + " 与 " + buffer2 + "相同");
}else {
   console.log(buffer1 + " 在 " + buffer2 + "之后");
}

Implementation of the above code, the output is:

ABC在ABCD之前

Copy buffer

grammar

Node buffer copy syntax is as follows:

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

parameter

Parameters are described below:

  • targetBuffer - Buffer objects you want to copy.

  • targetStart - digital, optional, default: 0

  • sourceStart - digital, optional, default: 0

  • sourceEnd - digital, optional, default: buffer.length

return value

No return value.

Examples

var buffer1 = new Buffer('ABC');
// 拷贝一个缓冲区
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());

Implementation of the above code, the output is:

buffer2 content: ABC

Crop Buffer

Node buffer crop syntax is as follows:

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

parameter

Parameters are described below:

  • start - numbers, optional, default: 0

  • end - digital, optional, default: buffer.length

return value

Returns a new buffer, it is old and point to the same piece of memory buffer, but start from the index to the location of the cut end.

Examples

var buffer1 = new Buffer('w3big');
// 剪切缓冲区
var buffer2 = buffer1.slice(0,2);
console.log("buffer2 content: " + buffer2.toString());

Implementation of the above code, the output is:

buffer2 content: ru

Buffer length

grammar

Node buffer length calculation syntax is as follows:

buf.length;

return value

Back Buffer memory occupied by the object length.

Examples

var buffer = new Buffer('www.w3big.com');
//  缓冲区长度
console.log("buffer length: " + buffer.length);

Implementation of the above code, the output is:

buffer length: 14

Method Reference Manual

Following is a list Node.js Buffer module commonly used method (Note that some methods in the old version is not):

No. Method & description
1 new Buffer (size)
Assign a new size for the size of the unit 8 byte buffer. Note, size must be less than kMaxLength, otherwise, it will throw an exception RangeError.
2 new Buffer (buffer)
Parameter copy data to the buffer Buffer instance.
3 new Buffer (str [, encoding] )
It allocates a new buffer, which contains the string passed in str. encoding encoding defaults to 'utf8'.
4 buf.length
Returns the number of bytes in the buffer. Note that this is not necessarily the size of the buffer inside the content. length buffer is the amount of memory allocated by the object, it does not change the buffer with the contents of the object changes.
5 buf.write (string [, offset [, length]] [, encoding])
According to the offset and offset parameters specified encoding encoding, writes the buffer parameter string data. offset Offset The default value is 0, encoding the default encoding is utf8. length length size bytes to be written string. Returns the number type, write the number eight represents the byte stream. If the buffer is not enough space to put the entire string, it will only be written only part of the string. The default length is buffer.length - offset. This method to write some characters do not appear.
6 buf.writeUIntLE (value, offset, byteLength [ , noAssert])
The value is written to the buffer where it is determined by the offset and byteLength, support 48-bit computing, for example:
var b = new Buffer(6);
b.writeUIntBE(0x1234567890ab, 0, 6);
// <Buffer 12 34 56 78 90 ab>
noAssert when value is true, no longer verify the validity and value of the offset. The default is false.
7 buf.writeUIntBE (value, offset, byteLength [ , noAssert])
The value is written to the buffer where it is determined by the offset and byteLength, support 48-bit computing. noAssert when value is true, no longer verify the validity and value of the offset. The default is false.
8 buf.writeIntLE (value, offset, byteLength [ , noAssert])
The value is written to the buffer where it is determined by the offset and byteLength, support 48-bit computing. noAssert when value is true, no longer verify the validity and value of the offset. The default is false.
9 buf.writeIntBE (value, offset, byteLength [ , noAssert])
The value is written to the buffer where it is determined by the offset and byteLength, support 48-bit computing. noAssert when value is true, no longer verify the validity and value of the offset. The default is false.
10 buf.readUIntLE (offset, byteLength [, noAssert ])
Support reading digital 48 or less. When noAssert is true, offset no longer verify that exceeds buffer length, the default is false.
11 buf.readUIntBE (offset, byteLength [, noAssert ])
Support reading digital 48 or less. When noAssert is true, offset no longer verify that exceeds buffer length, the default is false.
12 buf.readIntLE (offset, byteLength [, noAssert ])
Support reading digital 48 or less. When noAssert is true, offset no longer verify that exceeds buffer length, the default is false.
13 buf.readIntBE (offset, byteLength [, noAssert ])
Support reading digital 48 or less. When noAssert is true, offset no longer verify that exceeds buffer length, the default is false.
14 buf.toString ([encoding [, start [ , end]]])
(The default is 'utf8') returns a string of decoded according to the type of encoding parameters. It will be based on the parameters passed start (default is 0) and end (default is buffer.length) as a range of values.
15 buf.toJSON ()
The Buffer instance into a JSON object.
16 buf [index]
Gets or sets the specified bytes. The return value represents a byte, so the legal range of the return value is 0x00 to 0xFF hex or decimal 0-255.
17 buf.equals (otherBuffer)
Compare two buffers are equal, and if returns true, otherwise returns false.
18 buf.compare (otherBuffer)
Buffer compare two objects and returns a number that represents buf before otherBuffer, or after the same.
19 buf.copy (targetBuffer [, targetStart [, sourceStart [, sourceEnd]]])
copy buffer, the source and destination can be the same. targetStart Target Start offset and sourceStart source start offset default is 0. sourceEnd source end position is offset default length buffer.length source.
20 buf.slice ([start [, end] ])
Cut Buffer objects, according to the start (default is 0) and end (default is buffer.length) offset and crop index. Negative index is calculated from the beginning of the tail buffer.
twenty one buf.readUInt8 (offset [, noAssert])
According to the specified offset Reads a signed 8-bit integer. If the parameter is true noAssert will not validate offset offset parameters. If this offset may be beyond the end of the buffer. The default is false.
twenty two buf.readUInt16LE (offset [, noAssert])
According to the specified offset using special endian byte order format Reads a signed 16-bit integer. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
twenty three buf.readUInt16BE (offset [, noAssert])
According to the specified offset using special endian byte order format Reads a signed 16-bit integer. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
twenty four buf.readUInt32LE (offset [, noAssert])
According to the specified offset with the specified endian byte order format Reads a signed 32-bit integer. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
25 buf.readUInt32BE (offset [, noAssert])
According to the specified offset with the specified endian byte order format Reads a signed 32-bit integer. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
26 buf.readInt8 (offset [, noAssert])
According to the specified offset, to read a signed 8-bit integer. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
27 buf.readInt16LE (offset [, noAssert])
According to the specified offset using special endian format reads a signed 16-bit integer. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
28 buf.readInt16BE (offset [, noAssert])
According to the specified offset using special endian format reads a signed 16-bit integer. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
29 buf.readInt32LE (offset [, noAssert])
According to the specified offset with the specified endian byte order format reads a signed 32-bit integer. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
30 buf.readInt32BE (offset [, noAssert])
According to the specified offset with the specified endian byte order format reads a signed 32-bit integer. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
31 buf.readFloatLE (offset [, noAssert])
According to the specified offset with the specified endian byte order to read a 32-bit floating-point format. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
32 buf.readFloatBE (offset [, noAssert])
According to the specified offset with the specified endian byte order to read a 32-bit floating-point format. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
33 buf.readDoubleLE (offset [, noAssert])
According to the specified offset with the specified endian byte order format to read a 64-bit double. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
34 buf.readDoubleBE (offset [, noAssert])
According to the specified offset with the specified endian byte order format to read a 64-bit double. If the parameter is true noAssert will not validate offset offset parameters. This means that the offset may be beyond the end of the buffer. The default is false.
35 buf.writeUInt8 (value, offset [, noAssert ])
According to the incoming offset the offset value write buffer. Note: value must be a valid signed 8-bit integer. If the parameter is true noAssert will not validate offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, do not use. The default is false.
36 buf.writeUInt16LE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: value must be a valid 16-bit signed integer. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
37 buf.writeUInt16BE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: value must be a valid 16-bit signed integer. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
38 buf.writeUInt32LE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: value must be a valid 32-bit signed integer. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
39 buf.writeUInt32BE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: value must be a valid 32-bit signed integer. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
40 buf.writeInt8 (value, offset [, noAssert ])
41 buf.writeInt16LE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: value must be a valid signed 16-bit integer. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
42 buf.writeInt16BE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: value must be a valid signed 16-bit integer. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
43 buf.writeInt32LE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: value must be a valid signed 32-bit integer. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
44 buf.writeInt32BE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: value must be a valid signed 32-bit integer. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
45 buf.writeFloatLE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: When the value is not the value of a 32-bit floating-point type, the result is undefined. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
46 buf.writeFloatBE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: When the value is not the value of a 32-bit floating-point type, the result is undefined. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
47 buf.writeDoubleLE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: value must be a valid 64-bit value of type double. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
48 buf.writeDoubleBE (value, offset [, noAssert ])
According to the incoming offset offset and the specified endian format value write buffer. Note: value must be a valid 64-bit value of type double. If the parameter is noAssert true value will not be validated and offset offset parameters. This means that the value may be too large, or offset may exceed the end of the buffer the resulting value is discarded. Unless you are very sure about this parameter, or try not to use. The default is false.
49 buf.fill (value [, offset] [ , end])
Using the specified value to fill the buffer. If no offset (the default is 0) and end (default is buffer.length), will fill the entire buffer.