0
0
Node.jsframework~5 mins

Buffer concatenation in Node.js

Choose your learning style9 modes available
Introduction
Buffer concatenation lets you join multiple pieces of binary data into one. This helps when you want to combine small chunks of data into a bigger piece.
When receiving data in parts from a network and you want to join it before processing.
When combining multiple files or data streams into one buffer.
When building a message from smaller binary pieces before sending it.
When you want to merge image or audio data stored in buffers.
When you need to assemble chunks of data read from disk into a single buffer.
Syntax
Node.js
Buffer.concat(list[, totalLength])
list is an array of Buffer objects you want to join.
totalLength is optional and tells Node.js the final size to optimize memory.
Examples
Joins two buffers containing text into one buffer.
Node.js
const buf1 = Buffer.from('Hello, ');
const buf2 = Buffer.from('world!');
const result = Buffer.concat([buf1, buf2]);
Concatenates three buffers holding numbers as strings.
Node.js
const parts = [Buffer.from('123'), Buffer.from('456'), Buffer.from('789')];
const combined = Buffer.concat(parts);
Joins two buffers with a specified total length for efficiency.
Node.js
const bufA = Buffer.alloc(5, 'a');
const bufB = Buffer.alloc(3, 'b');
const combined = Buffer.concat([bufA, bufB], 8);
Sample Program
This program creates three buffers with text, joins them into one buffer, and prints the combined string.
Node.js
const buf1 = Buffer.from('Node.js ');
const buf2 = Buffer.from('Buffer ');
const buf3 = Buffer.from('Concatenation');

const combined = Buffer.concat([buf1, buf2, buf3]);

console.log(combined.toString());
OutputSuccess
Important Notes
Buffer.concat does not change the original buffers; it creates a new one.
If you know the total length of the final buffer, passing it helps Node.js allocate memory faster.
Always convert buffers to strings with toString() to see readable text.
Summary
Buffer.concat joins multiple buffers into one bigger buffer.
It is useful when working with data in chunks, like network or file data.
You can optionally provide the total length for better performance.