0
0
NodejsHow-ToBeginner · 3 min read

How to Concatenate Buffers in Node.js: Simple Guide

In Node.js, you can concatenate buffers using the Buffer.concat() method, which takes an array of buffers and returns a new combined buffer. This method efficiently joins multiple buffers into one without manual copying.
📐

Syntax

The Buffer.concat() method combines multiple buffers into a single buffer.

  • buffers: An array of Buffer objects to concatenate.
  • totalLength (optional): The total length of the resulting buffer. If omitted, Node.js calculates it automatically.
javascript
Buffer.concat(buffers[, totalLength])
💻

Example

This example shows how to concatenate two buffers containing text and print the combined result as a string.

javascript
const buf1 = Buffer.from('Hello, ');
const buf2 = Buffer.from('world!');
const combined = Buffer.concat([buf1, buf2]);
console.log(combined.toString());
Output
Hello, world!
⚠️

Common Pitfalls

One common mistake is forgetting to pass an array of buffers to Buffer.concat(). Passing individual buffers instead of an array will cause an error. Another issue is not specifying totalLength when concatenating many buffers, which can affect performance.

javascript
/* Wrong way: passing buffers directly */
// Buffer.concat(buf1, buf2); // This throws an error

/* Right way: pass an array */
const combined = Buffer.concat([buf1, buf2]);
📊

Quick Reference

Use Buffer.concat() to join buffers efficiently. Pass an array of buffers and optionally the total length for better performance.

MethodDescription
Buffer.concat(buffers)Concatenates an array of buffers into one buffer.
Buffer.concat(buffers, totalLength)Concatenates buffers with a specified total length for optimization.

Key Takeaways

Use Buffer.concat() with an array of buffers to combine them.
Optionally provide totalLength for better performance with many buffers.
Always pass an array, not individual buffers, to Buffer.concat().
The result is a new buffer containing all data in order.
Convert the combined buffer to string with toString() if needed.