Open In App

Which module is used for buffer based operations in Node.js ?

The module which is used for buffer-based operation is the buffer module.

Buffer Module: The buffers module provides a way of handling streams of binary data. Buffers are designed to handle binary raw data. Buffers allocate raw memory outside the V8 heap. The Buffer object is a global object in Node.js, and it is not important to import it using the required keyword.



Syntax:

const buf = Buffer.alloc(n);

Here, n is the integer number for the size of the buffer.



Example 1: Writing in buffers.

In the below example we have used buf.write() method to write data into a node buffer.

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




const cbuf = Buffer.alloc(256);
bufferlen = cbuf.write("Let's do this 
    with GeeksForGeeks");
console.log("No. of Octets in which 
    string is written : "+  bufferlen);

Output:

The above code creates a buffer file and gives the expected output. 

Example 2: Read the data from Node.js buffer specifying the start and endpoint of reading. Create a buffer.js file containing the following code.

The buf.toString() method accepts the following parameters:  

Syntax:

buf.toString( encoding, start, end )




const rbuf = Buffer.alloc(26);
let j;
  
for (let i = 65, j = 0; i < 90, j < 26; i++, j++) {
    rbuf[j] = i;
}
  
console.log(rbuf.toString('utf-8', 3, 9));

The above code reads from a file from the starting point which we specify and prints the output on the terminal 


Article Tags :