Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 )
  • string: It specifies the string data which is to be written into the buffer.
  • offset: It specifies the index at which buffer starts writing. Its default value is 0.
  • length: It specifies the number of bytes to write. Its default value is buffer.length.
  • encoding: It specifies the encoding mechanism. Its default value is ‘utf-8’.

Javascript




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 )
  • encoding: It specifies the encoding mechanism. Its default value is ‘utf-8’.
  • start: It specifies the index to start reading. Its default value is 0.
  • end: It specifies the index to end reading. Its default value is a complete buffer.

Javascript




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 


My Personal Notes arrow_drop_up
Last Updated : 27 Mar, 2022
Like Article
Save Article
Similar Reads
Related Tutorials