Buffer.concat(list[, totalLength])


返回新的 Buffer,它是将 list 中的所有 Buffer 实例连接在一起的结果。

如果列表没有条目,或者 totalLength 为 0,则返回新的零长度 Buffer

如果未提供 totalLength,则从 list 中的 Buffer 实例通过相加其长度来计算。

如果提供了 totalLength,则将其强制为无符号整数。 如果 listBuffer 的组合长度超过 totalLength,则结果截断为 totalLength

// 从三个 `Buffer` 实例的列表创建单个 `Buffer`。

const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;

console.log(totalLength);
// 打印: 42

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

console.log(bufA);
// 打印: <Buffer 00 00 00 00 ...>
console.log(bufA.length);
// 打印: 42

Buffer.concat() 也像 Buffer.allocUnsafe() 一样使用内部 Buffer 池。

Returns a new Buffer which is the result of concatenating all the Buffer instances in the list together.

If the list has no items, or if the totalLength is 0, then a new zero-length Buffer is returned.

If totalLength is not provided, it is calculated from the Buffer instances in list by adding their lengths.

If totalLength is provided, it is coerced to an unsigned integer. If the combined length of the Buffers in list exceeds totalLength, the result is truncated to totalLength.

// Create a single `Buffer` from a list of three `Buffer` instances.

const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;

console.log(totalLength);
// Prints: 42

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

console.log(bufA);
// Prints: <Buffer 00 00 00 00 ...>
console.log(bufA.length);
// Prints: 42

Buffer.concat() may also use the internal Buffer pool like Buffer.allocUnsafe() does.