• Node.js Video Tutorials

Node.js - Buffer.concat() Method



The NodeJS Buffer.concat() method will return a single buffer object by concatenating all the given buffer objects. If the buffers used have no items or the length of the buffers is 0, the final buffer created will be a new zero-length buffer.

Syntax

Following is the syntax of the Node.JS Buffer.concat() Method

Buffer.concat( array, length )

Parameters

This method accepts two parameters. The same is explained below.

  • array −(required) An array of buffers that needs to be concatenated.

  • length −(optional). The length you want for the final concatenated buffer. If not given the length will be the sum of the given buffer lengths used in concat().

Return value

The method Buffer.concat() will return a buffer with its length equivalent to the length of the buffers used in concatenating or unless specified by using the length parameter in buffer.concat().

Example

The example will create a new buffer using NodeJS buffer.concat() method.

const buffer1 = Buffer.from('A');
const buffer2 = Buffer.from('B');
const buffer3 = Buffer.from('C');
var myarray = [buffer1, buffer2, buffer3];
var newBuffer = Buffer.concat(myarray);
console.log(newBuffer);
console.log("The length of new buffer is : "+newBuffer.length);

Output

<Buffer 41 42 43>
The length of new buffer is : 3

Example

In this example let us create a new buffer and also specify the length of the buffer.

const buffer1 = Buffer.from('Hello');
const buffer2 = Buffer.from('How');
const buffer3 = Buffer.from('are you!');
var myarray = [buffer1, buffer2, buffer3];
var newBuffer = Buffer.concat(myarray, 10);
console.log(newBuffer);
console.log(newBuffer.toString());
console.log("The length of new buffer is : "+newBuffer.length);

Output

The length of the final buffer given is 10. Even though the buffers in the array has length more than the specified length, it will still fall back to the length specified. You can check the same in the output.

<Buffer 48 65 6c 6c 6f 48 6f 77 61 72>
HelloHowar
The length of new buffer is : 10

Example

The example will create a new buffer using the buffer.concat() method by using Buffer.alloc() and Buffer.fill().

const buffer1 = Buffer.alloc(5);
const buffer2 = Buffer.alloc(5);
buffer1.fill('H');
buffer2.fill('W');
var myarray = [buffer1, buffer2];
var newBuffer = Buffer.concat(myarray);
console.log(newBuffer);
console.log("The length of new buffer is : "+newBuffer.length);

Output

<Buffer 48 48 48 48 48 57 57 57 57 57>
The length of new buffer is : 10
nodejs_buffer_module.htm
Advertisements