What is fill() in Node.js Buffer Module?
The fill function in Node.js Buffer Module
The fill function is a member function of Buffer class in the Node.js Buffer Module. The syntax of the fill function is as follows:
buf.fill(value[,offset[,end]][,encoding])
Parameters
valueis the value that is used to fill the buffer. It can be any of the following types:stringBufferUint8Arrayinteger
offsetis anintegerthat specifies the number of bytes to skip from the start of the buffer when filling it. The default value is0.endis anintegerthat specifies up to which byte the buffer must be filled (exclusive). The default value isbuf.length.encodingis astringthat specifies the encoding type for thevalueparameter if it is astring. The default value isutf-8.
Return value
- Returns a reference to
bufof typeBuffer.
Description
The fill function fills the buffer buf with the specified value.
Example usage of the fill function
The following code snippet provides various examples on how to use the fill function:
const buffers = []// Create and store 5 buffers with length 10 and fill with 'x'sfor (let i = 0; i < 5; i++) {buffers.push(Buffer.alloc(10, 'x'));}buffers[0].fill('a');buffers[1].fill('b', 5);buffers[2].fill('c', 5, 9);buffers[3].fill('dd', 'hex');buffers[4].fill('e', 5, 8, 'utf-8');for (let i = 0; i < 3; i++) {console.log(`Buffer[${i}] as String:`);console.log(buffers[i].toString());}console.log('Buffer[3]:')console.log(buffers[3]);console.log('Buffers[4] as String:');console.log(buffers[4].toString());
In the above example, the array buffers is initialized with 5 Buffer instances of length 10 that are filled with x. buffers[0].fill is called with only the value argument and results in the whole buffer being filled with a. buffers[1].fill is supplied the offset value 5, so in the output, bs occurred at and after the index 5 of the buffer, keeping the first 5 bytes unchanged. buffers[2].fill is supplied offset and end, which have the values 5 and 9 respectively.
Note that
cwas filled up to the index9of the buffer (excluding index 9 itself).
buffers[3].fill is called with value and encoding arguments, which have the values dd and hex respectively. The string dd, if interpreted as a utf-8 string, yields two bytes, one for each d. However, in this case, dd is interpreted as a hex string; since a single digit in hex is equivalent to half a byte, the string dd yields a single byte. buffer[3] is printed as a buffer which shows the values in hexadecimal notation, where 2 characters separated by a space represent a single byte. buffers[4].fill is supplied all parameters; value, offset, end, and encoding. The value e is filled starting from the index 5 byte and is filled up to the index 8 byte (exclusive).
Free Resources