Open In App

Node.js Buffers

Buffers are instances of the Buffer class in Node.js. Buffers are designed to handle binary raw data. Buffers allocate raw memory outside the V8 heap. Buffer class is a global class so it can be used without importing the Buffer module in an application.
Creating Buffers: Followings are the different ways to create buffers in Node.js:
 

var ubuf = Buffer.alloc(5);
var abuf = new Buffer([16, 32, 48, 64]);
var sbuf = new Buffer("GeeksforGeeks", "ascii");

Writing to Buffers in Node.js: The buf.write() method is used to write data into a node buffer.
Syntax: 
 



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

The buf.write() method is used to return the number of octets in which string is written. If buffer does not have enough space to fit the entire string, it will write a part of the string. 
The buf.write() method accepts the following parameters: 
 

Example: Create a buffer.js file containing the following codes.
 






// Write JavaScript code here
cbuf = new Buffer(256);
bufferlen = cbuf.write("Learn Programming with GeeksforGeeks!!!");
console.log("No. of Octets in which string is written : "+  bufferlen);

Output: 
 

Reading from Buffers: The buf.toString() method is used to read data from a node buffer. 
Syntax: 
 

buf.toString( encoding, start, end )

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

Example 1: Create a buffer.js file containing the following code.
 




// Write JavaScript code here
rbuf = new Buffer(26);
var j;
 
for (var i = 65, j = 0; i < 90, j < 26; i++, j++) { 
    rbuf[j] = i ; 
 
console.log( rbuf.toString('ascii')); 

Output: 
 

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




// Write JavaScript code here
rbuf = new Buffer(26); 
var j;
 
for (var i = 65, j = 0; i < 90, j < 26; i++, j++) { 
    rbuf[j] = i ; 
}
 
console.log( rbuf.toString('utf-8', 3, 9)); 

Output: 
 

 


Article Tags :