Loading, please wait...

Node.js Buffer

Node.js Buffer

The Buffer class has introduced as part of the Node.js API to enable interaction with octet streams in TCP stream and file system operation. Buffer class is a global class this can be accessed in an application without importing the buffer module.

How to create Buffer: there are different ways to create a buffer in node.js

Method 1:

Following is the syntax to create an uninitiated Buffer of 10 octets

var buf =new Buffer(10);

Method 2:

Following is the syntax to create a Buffer from a given array

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

Method 3:

Following is the syntax to create a Buffer from a given string and optionally encoding type

var buf = new Buffer("Tutorial link is E-learning portal", "utf-8");

Though "utf8" is the default encoding, we can use any of the following encodings "ascii", "utf8", "utf16le", "ucs2", "base64" or "hex".

Writing to Buffers

Parameters:

  • 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.
  • Length – This is the number of bytes to write.
  • Encoding – ‘Utf8’ is the default encoding.

 Example:

Run the code:

Reading from Buffers

Syntax:

Parameters

  • Encoding− to use. 'utf8' is the default encoding.
  • Start− Beginning index to start reading, defaults to 0.
  • End− index to end reading defaults is a complete buffer.

      Example

 

  Run the code:

Convert Buffer to JSON             

Syntax:

Example:

Execute the code:

Concatenate Buffers

Syntax:

Parameters:

List − Array List of Buffer objects to be concatenated.

  • Total Length− This is the total length of the buffers when concatenated.

Example

Run the code:

Compare Buffer

Following is the syntax of the method to compare two Node buffers-

Syntax:

Parameters

Here is the description of the parameters used

Other Buffer − this is the other buffer which will be compared with buf.

Example:

Run the code:

Copy Buffer

Syntax

Following is the syntax of the method to copy a node buffer –

Parameters

Here is the description of the parameters used −

  • targetBuffer− Buffer object where buffer will be copied.
  • targetStart− Number, Optional, Default: 0
  • sourceStart− Number, Optional, Default: 0
  • sourceEnd− Number, Optional, Default: buffer.length.

Return Value

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 source End defaults to buffer.length.

  Example:

     Execute the code: