The Buffer.concat()
function combines multiple instances of buffers into a single buffer and returns it.
The Buffer.concat()
function accepts the following parameters:
list
: A list of all the buffer instances that the function concatenates.totalLength
: The sum of the individual lengths of all the buffers, input to the function as type integer.If list
is empty or totalLength
is zero, the Buffer.concat()
function returns a buffer of zero length.
If totalLength
is not input, the Buffer.concat()
function deduces the length from the given list
. If the actual total length of the buffers is greater than the totalLength
, the function truncates the final buffer to fit into the size given by totalLength
.
Note: The
Buffer.concat()
function convertstotalLength
into an unsigned integer.
The following code demonstrates how to use the Buffer.concat()
function in Node.js.
Buffer.from()
.buf.length
and concatenates the three buffers.// create buffersconst buf1 = Buffer.from("this")console.log(buf1)const buf2 = Buffer.from("is a")console.log(buf2)const buf3 = Buffer.from("test string")console.log(buf3)//calculate total lengthconst len = buf1.length + buf2.length +buf3.lengthconst arr = [buf1, buf2, buf3]//conactenatconst concatbuf = Buffer.concat(arr, len)console.log(concatbuf)
Free Resources