Open In App

Node.js Buffer.fill() Method

Buffer is a temporary memory storage that stores the data when it is being moved from one place to another. It’s like an array of integers. The Buffer.fill() Method puts the data into the buffer instance. If the offset and end values are not given then the complete buffer will be filled. 

Syntax:



buffer.fill( string, offset, end, encoding )

Parameters: This method accepts four parameters as mentioned above and described below:

Return Value: This method returns a buffer object containing the values. 



Example 1: The below example illustrates the use of Buffer.fill() method in Node.js:




// Node.js program to demonstrate the
// Buffer.fill() Method
 
// Allocating the space to buffer instance
const buffer = Buffer.alloc(13);
 
buffer.fill('GeeksforGeeks');
 
console.log(buffer.toString());

Output:

GeeksforGeeks

Example 2: The below example illustrates the use of the Buffer.fill() method in Node.js:




// Node.js program to demonstrate the
// Buffer.fill() Method
 
// Allocating the space to buffer instance
const buffer = Buffer.alloc(7);
 
buffer.fill('geek', 3);
 
// Prints : ' geek' as we are starting
// from index 3 to fill the buffer
console.log(buffer.toString());

Output: 

   geek

Note: The above program will compile and run by using the node index.js command.

Reference: https://nodejs.org/api/buffer.html#buffer_buf_fill_value_offset_end_encoding

Article Tags :