Copying and Concatenating Buffers
You'll learn how to duplicate buffer data and merge multiple buffers into one.
Understanding Buffer Duplication and Merging
When working with binary data, you'll often need to copy a buffer to preserve data while modifying it elsewhere, or combine multiple buffers into a single continuous sequence. Think of copying like making a photocopy of a document—changes to the copy don't affect the original. Concatenating is like stapling several pages together into one packet.
Copying Buffers
Use the copy() method to duplicate buffer data into another buffer. You need to create a target buffer first:
const source = Buffer.from('Hello');
const target = Buffer.alloc(5);
source.copy(target);
console.log(target.toString()); // 'Hello'
// Partial copy starting at index 1
const partial = Buffer.alloc(3);
source.copy(partial, 0, 1, 4); // targetStart, sourceStart, sourceEnd
console.log(partial.toString()); // 'ell'
Concatenating Buffers
Buffer.concat() merges an array of buffers into a single buffer:
const buf1 = Buffer.from('Hello');
const buf2 = Buffer.from(' ');
const buf3 = Buffer.from('World');
const combined = Buffer.concat([buf1, buf2, buf3]);
console.log(combined.toString()); // 'Hello World'
// Optional length parameter pre-allocates size
const sized = Buffer.concat([buf1, buf2], 6);
console.log(sized.toString()); // 'Hello '
The concat method is especially useful when accumulating data from streams or combining fragments received over a network.
Key Takeaway: Use copy() to duplicate buffer contents into an existing buffer, and Buffer.concat() to merge multiple buffers into one—essential operations for managing binary data in Node.js applications.