Home >>Nodejs Tutorial >Node.js - Buffers

Node.js - Buffers

Node.js - Buffers

Pure JavaScript is friendly to Unicode, but for binary data this is not so. It is essential to handle octet streams while dealing with TCP streams or the file system. Node provides a buffer class that provides instances for storing raw data similar to an array of integers which corresponds to an allocation of raw memory outside the V8 heap.

Buffer class is a global class that can be accessed within an application without the buffer module being imported.

Creating Buffers

Node buffer can be developed in a number of ways.

Method 1

Next is the syntax to construct a 10-byte uninitiated buffer-

var buf = new Buffer(10);
Method 2

The syntax to create a buffer from a given array follows –

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

The syntax follows to construct a buffer from a given string and optionally encode type –

var buf = new Buffer("Simply Easy Learning", "utf-8");

Although "utf8" is the default encoding, you can use "ascii," "utf16le," "utf8," "ucs2," "base64" or "hex."

Writing to Buffers

Syntax:

The method to write to a Node Buffer is syntaxed below

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

Parameters Value

The description of the parameters used is here-

Parameters Description
String− This is the data string to buffer to write.
Offset− This is the buffer index for starting writing to. Defaults to 0.
Length− This is the number of writable bytes. Buffer.length defaults to.
Encoding− Usable encoding. Its default encoding is 'utf8.'
Return Value

This method returns written octet numbers. If there is not enough space in the buffer to suit the whole string, a section of the string is written.

Example

buf = new Buffer(256);
len = buf.write("Hello Phptpoint");
console.log("Octets written : "+  len);

when you can executed the above program, it will produces the following result –
Octets written : 15

Reading from Buffers

Syntax

Following is the method syntax for reading data from a Node Buffer –

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

Parameter Values

Parameter Description
Encoding− Usable encoding. Its default encoding is 'utf8.'
Start− Starts read index, defaults to 0.
End− End index to finish reading, default buffer is complete.
Return Value

This method decodes and returns a string from encoded buffer data using the encoding of the specified character set.

Example

buf = new Buffer(22);
for (var i = 0 ; i < 22 ; i++) 
{
buf[i] = i + 97;
}
console.log( buf.toString('ascii'));    
console.log( buf.toString('ascii',0,5));   
console.log( buf.toString('utf8',0,5));   
console.log( buf.toString(undefined,0,5));

When the above program is executed, the result will be the following-
abcdefghijklmnopqrstuv
abcde
abcde
abcde

Convert Buffer to JSON

Syntax

Following is the method syntax for converting a Node Buffer to JSON object –

buf.toJSON()
Return Value

This method returns the Buffer instance a JSON-representation.

Example

var buf = new Buffer('Hello Phptpoint');
var json = buf.toJSON(buf);
console.log(json);

When the above program is executed, the result will be the following-
{ type: 'Buffer',
data:
[
72,
101,
108,
108,
111,
32,
80,
104,
112,
116,
112,
111,
105,
110,
116
]
}

Concatenate Buffers

Syntax

The method to concatenate node buffers to a single node buffer is syntaxed below.

Buffer.concat(list[, totalLength])

Parameter Value

The description of the parameters is used here-

Return Value

This method returns an instance of a Buffer.

Parameters Description
List− Array List of objects to concatenate with buffer.
TotalLength− When concatenated, the total length of the buffers is.
Example

var buffer1 = new Buffer('Phptpoint ');
var buffer2 = new Buffer('Hello phptpoint');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 content: " + buffer3.toString());

When the above program is executed, the result will be the following-
buffer3 content: Phptpoint Hello phptpoint

Compare Buffers

Syntax

Following is the method syntax for comparing two Node buffers –

buf.compare(otherBuffer);

Parameter Values

The description of the parameters is used here-

Parameters Description
OtherBuffer− This is another buffer to be compared to buf
Return Value

Returns a number that indicates whether it is in sort order before or after, or is the same as the otherBuffer.

Example

var buffer1 = new Buffer('WXY');
var buffer2 = new Buffer('WXYZ');
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, the result will be the following-
WXY comes before WXYZ

Copy Buffer

Syntax

The method for copying a node buffer is syntaxed below –

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

Parameter Values

The description of the parameters is used here-

Parameter Description
TargetBuffer− Buffer object to copy buffer to.
targetStart− Number, Optional, Default: 0
sourceStart− Number, Optional, Default: 0
sourceEnd− Number, Optional, Default: buffer.length
Return Value

No value for return. Copies data in the target buffer from a region of this buffer to a region even if the target memory region overlaps with the source. If undefined, the default parameters for targetStart and sourceStart are 0, while default to buffer.length is for sourceEnd.

Example

var buffer1 = new Buffer('XYZ');
//copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());\

When the above program is executed, the result will be the following-
buffer2 content: XYZ

Slice Buffer

Syntax

Following is the method syntax for getting a node buffer sub-buffer –

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

Parameter Values

The description of the parameters is used here-

Parameter Description
start− Number, Optional, Default: 0
end− Number, Optional, Default: buffer.length
Return Value

Returns a new buffer referring to the same memory as the old one but offsetting and cropped by the indexes start (defaults to 0) and end (defaults to buffer.length). Negative indexes start at buffer ends.

Example

var buffer1 = new Buffer('Phptpoint');
//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());

When the above program is executed, the result will be the following-
buffer2 content: Phptpoint

Buffer Length

Syntax

The syntax of the method to get a node buffer size in bytes follows –

buf.length;
Return Value

Returns in Bytes the size of a buffer

Example

var buffer = new Buffer('phptpoint');
//length of the buffer
console.log("buffer length: " + buffer.length);

When the above program is executed it results –
buffer length: 9

Class Methods

Sr No Method & Description
1 Buffer.isEncoding(encoding)
Returns true if the encoding argument is valid, otherwise false.
2 Buffer.isBuffer(obj)
Tests if obj is a Buffer.
3 Buffer.byteLength(string[, encoding])
Gives a string's actual Byte length. Default encoding to 'utf8.' It is not the same as String.prototype.length, since it returns the number of characters in a string.
4 Buffer.concat(list[, totalLength])
Returns a buffer that results in all the buffers in the list being concatenated together.
5 Buffer.compare(buf1, buf2)
The same is true of buf1.compare(buf2). Useful for sorting buffers in an array.