Node.js | Buffer.fill() Method

Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. Its like the array of integers.

The Buffer.fill() Method puts the data into the buffer instance. If the offset and end value are not given then the complete buffer will be filled.

Syntax:



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

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

  • string: It holds the data you need to put into the buffer.
  • start: The index from which you need to start filling the buffer. Its default value is 0.
  • end: The index till which you need to fill the buffer. The default value is buffer.length
  • encoding: The encoding for data if data is in string format. The default value is utf8.

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

Below examples illustrate the use of Buffer.fill() method in Node.js:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

GeeksforGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the  
// Buffer.fill() Method
  
// Allocating the space to buffer instance
var 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());

chevron_right


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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.