How to use the Buffer.concat() function in Node.js

The Buffer.concat() function combines multiple instances of buffers into a single buffer and returns it.

Prototype

Parameters

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 converts totalLength into an unsigned integer.

Example

The following code demonstrates how to use the Buffer.concat() function in Node.js.

  • The program creates three buffers through Buffer.from().
  • The program then calculates the total length through buf.length and concatenates the three buffers.
// create buffers
const 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 length
const len = buf1.length + buf2.length +buf3.length
const arr = [buf1, buf2, buf3]
//conactenat
const concatbuf = Buffer.concat(arr, len)
console.log(concatbuf)

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved