Node.js - Buffers

Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with TCP streams or the file system, it's necessary to handle octet streams. Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.
Buffer class is a global class that can be accessed in an application without importing the buffer module.
Node Buffer can be constructed in a variety of ways.
Following is the syntax to create an uninitiated Buffer of 10 octets −
var buf = new Buffer(10);

Following is the syntax to create a Buffer from a given array −
var buf = new Buffer([10, 20, 30, 40, 50]);

Following is the syntax to create a Buffer from a given string and optionally encoding type −
var buf = new Buffer("Simply Easy Learning", "utf-8");

Though "utf8" is the default encoding, you can use any of the following encodings "ascii", "utf8", "utf16le", "ucs2", "base64" or "hex".
Following is the syntax of the method to write into a Node Buffer −
buf.write(string[, offset][, length][, encoding])

Here is the description of the parameters used −
string − This is the string data to be written to buffer.
string − This is the string data to be written to buffer.
offset − This is the index of the buffer to start writing at. Default value is 0.
offset − This is the index of the buffer to start writing at. Default value is 0.
length − This is the number of bytes to write. Defaults to buffer.length.
length − This is the number of bytes to write. Defaults to buffer.length.
encoding − Encoding to use. 'utf8' is the default encoding.
encoding − Encoding to use. 'utf8' is the default encoding.
This method returns the number of octets written. If there is not enough space in the buffer to fit the entire string, it will write a part of the string.
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");

console.log("Octets written : "+  len);
When the above program is executed, it produces the following result −
Octets written : 20

Following is the syntax of the method to read data from a Node Buffer −
buf.toString([encoding][, start][, end])

Here is the description of the parameters used −
encoding − Encoding to use. 'utf8' is the default encoding.
encoding − Encoding to use. 'utf8' is the default encoding.
start − Beginning index to start reading, defaults to 0.
start − Beginning index to start reading, defaults to 0.
end − End index to end reading, defaults is complete buffer.
end − End index to end reading, defaults is complete buffer.
This method decodes and returns a string from buffer data encoded using the specified character set encoding.
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
  buf[i] = i + 97;
}

console.log( buf.toString('ascii'));       // outputs: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5));   // outputs: abcde
console.log( buf.toString('utf8',0,5));    // outputs: abcde
console.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde
When the above program is executed, it produces the following result −
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde

Following is the syntax of the method to convert a Node Buffer into JSON object −
buf.toJSON()

This method returns a JSON-representation of the Buffer instance.
var buf = new Buffer('Simply Easy Learning');
var json = buf.toJSON(buf);

console.log(json);
When the above program is executed, it produces the following result −
{ type: 'Buffer',
   data: 
   [ 
      83,
      105,
      109,
      112,
      108,
      121,
      32,
      69,
      97,
      115,
      121,
      32,
      76,
      101,
      97,
      114,
      110,
      105,
      110,
      103 
   ]
}

Following is the syntax of the method to concatenate Node buffers to a single Node Buffer −
Buffer.concat(list[, totalLength])

Here is the description of the parameters used −
list − Array List of Buffer objects to be concatenated.
list − Array List of Buffer objects to be concatenated.
totalLength − This is the total length of the buffers when concatenated.
totalLength − This is the total length of the buffers when concatenated.
This method returns a Buffer instance.
var buffer1 = new Buffer('TutorialsPoint ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);

console.log("buffer3 content: " + buffer3.toString());
When the above program is executed, it produces the following result −
buffer3 content: TutorialsPoint Simply Easy Learning

Following is the syntax of the method to compare two Node buffers −
buf.compare(otherBuffer);

Here is the description of the parameters used −
otherBuffer − This is the other buffer which will be compared with buf
otherBuffer − This is the other buffer which will be compared with buf
Returns a number indicating whether it comes before or after or is the same as the otherBuffer in sort order.
var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('ABCD');
var result = buffer1.compare(buffer2);

if(result < 0) {
   console.log(buffer1 +" comes before " + buffer2);
} else if(result === 0) {
   console.log(buffer1 +" is same as " + buffer2);
} else {
   console.log(buffer1 +" comes after " + buffer2);
}
When the above program is executed, it produces the following result −
ABC comes before ABCD

Following is the syntax of the method to copy a node buffer −
buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])

Here is the description of the parameters used −
targetBuffer − Buffer object where buffer will be copied.
targetBuffer − Buffer object where buffer will be copied.
targetStart − Number, Optional, Default: 0
targetStart − Number, Optional, Default: 0
sourceStart − Number, Optional, Default: 0
sourceStart − Number, Optional, Default: 0
sourceEnd − Number, Optional, Default: buffer.length
sourceEnd − Number, Optional, Default: buffer.length
No return value. Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to buffer.length.
var buffer1 = new Buffer('ABC');

//copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());
When the above program is executed, it produces the following result −
buffer2 content: ABC

Following is the syntax of the method to get a sub-buffer of a node buffer −
buf.slice([start][, end])

Here is the description of the parameters used −
start − Number, Optional, Default: 0
start − Number, Optional, Default: 0
end − Number, Optional, Default: buffer.length
end − Number, Optional, Default: buffer.length
Returns a new buffer which references the same memory as the old one, 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.
var buffer1 = new Buffer('TutorialsPoint');

//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());
When the above program is executed, it produces the following result −
buffer2 content: Tutorials

Following is the syntax of the method to get a size of a node buffer in bytes −
buf.length;

Returns the size of a buffer in bytes.
var buffer = new Buffer('TutorialsPoint');

//length of the buffer
console.log("buffer length: " + buffer.length);
When the above program is executed, it produces following result −
buffer length: 14

new Buffer(size)
Allocates a new buffer of size octets. Note that the size must be no more than kMaxLength. Otherwise, a RangeError will be thrown here.
new Buffer(buffer)
Copies the passed buffer data onto a new Buffer instance.
new Buffer(str[, encoding])
Allocates a new buffer containing the given str. encoding defaults to 'utf8'.
buf.length
Returns the size of the buffer in bytes. Note that this is not necessarily the size of the contents. length refers to the amount of memory allocated for the buffer object. It does not change when the contents of the buffer are changed.
buf.write(string[, offset][, length][, encoding])
Writes a 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 the number of octets written.
buf.writeUIntLE(value, offset, byteLength[, noAssert])
Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false.
buf.writeUIntBE(value, offset, byteLength[, noAssert])
Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false.
buf.writeIntLE(value, offset, byteLength[, noAssert])
Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false.
buf.writeIntBE(value, offset, byteLength[, noAssert])
Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false.
buf.readUIntLE(offset, byteLength[, noAssert])
A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.readUIntBE(offset, byteLength[, noAssert])
A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.readIntLE(offset, byteLength[, noAssert])
A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.readIntBE(offset, byteLength[, noAssert])
A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.toString([encoding][, start][, end])
Decodes and returns a string from buffer data encoded using the specified character set encoding.
buf.toJSON()
Returns a JSON-representation of the Buffer instance. JSON.stringify implicitly calls this function when stringifying a Buffer instance.
buf[index]
Get and set the octet at index. The values refer to individual bytes, so the legal range is between 0x00 and 0xFF hex or 0 and 255.
buf.equals(otherBuffer)
Returns a boolean if this buffer and otherBuffer have the same bytes.
buf.compare(otherBuffer)
Returns a number indicating whether this buffer comes before or after or is the same as the otherBuffer in sort order.
buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])
Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to buffer.length.
buf.slice([start][, end])
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.
buf.readUInt8(offset[, noAssert])
Reads an unsigned 8 bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.readUInt16LE(offset[, noAssert])
Reads an unsigned 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readUInt16BE(offset[, noAssert])
Reads an unsigned 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readUInt32LE(offset[, noAssert])
Reads an unsigned 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readUInt32BE(offset[, noAssert])
Reads an unsigned 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readInt8(offset[, noAssert])
Reads a signed 8-bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readInt16LE(offset[, noAssert])
Reads a signed 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readInt16BE(offset[, noAssert])
Reads a signed 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readInt32LE(offset[, noAssert])
Reads a signed 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readInt32BE(offset[, noAssert])
Reads a signed 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readFloatLE(offset[, noAssert])
Reads a 32-bit float from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readFloatBE(offset[, noAssert])
Reads a 32-bit float from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readDoubleLE(offset[, noAssert])
Reads a 64-bit double from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.readDoubleBE(offset[, noAssert])
Reads a 64-bit double from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false.
buf.writeUInt8(value, offset[, noAssert])
Writes a value to the buffer at the specified offset. Note that the value must be a valid unsigned 8-bit integer. Set noAssert to true to skip validation of value and offset. It means the 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. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeUInt16LE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of correctness. Defaults to false.
buf.writeUInt16BE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeUInt32LE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeUInt32BE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeInt8(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 8-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeInt16LE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeInt16BE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the 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. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeInt32LE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeInt32BE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of correctness. Defaults to false.
buf.writeFloatLE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means that the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeFloatBE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeDoubleLE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-bit double. Set noAssert to true to skip validation of value and offset. It 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. It should not be used unless you are certain of its correctness. Defaults to false.
buf.writeDoubleBE(value, offset[, noAssert])
Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-bit double. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false.
buf.fill(value[, offset][, end])
Fills the buffer with the specified value. If the offset (defaults to 0) and end (defaults to buffer.length) are not given, it will fill the entire buffer.
Buffer.isEncoding(encoding)
Returns true if the encoding is a valid encoding argument, false otherwise.
Buffer.isBuffer(obj)
Tests if obj is a Buffer.
Buffer.byteLength(string[, encoding])
Gives the actual byte length of a string. encoding defaults to 'utf8'. It is not the same as String.prototype.length, since String.prototype.length returns the number of characters in a string.
Buffer.concat(list[, totalLength])
Returns a buffer which is the result of concatenating all the buffers in the list together.
Buffer.compare(buf1, buf2)
The same as buf1.compare(buf2). Useful for sorting an array of buffers.

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    88 Lectures 
     17 hours 

 Eduonix Learning Solutions

    32 Lectures 
     1.5 hours 

 Richard Wells

    8 Lectures 
     33 mins

 Anant Rungta

    9 Lectures 
     2.5 hours 

 SHIVPRASAD KOIRALA

    97 Lectures 
     6 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page