静态方法:Buffer.concat(list[, totalLength])
【Static method: Buffer.concat(list[, totalLength])】
- '列表' <Uint8Array[]> “缓冲区”或 <Uint8Array> 实例列表,用于串接。
totalLength<integer> 将list中的Buffer实例连接后得到的总长度。- 返回:<Buffer>
返回一个新的 Buffer,它是将 list 中的所有 Buffer 实例连接在一起的结果。
【Returns a new Buffer which is the result of concatenating all the Buffer
instances in the list together.】
如果列表没有项目,或者 totalLength 为 0,则会返回一个新的零长度 Buffer。
【If the list has no items, or if the totalLength is 0, then a new zero-length
Buffer is returned.】
如果未提供 totalLength,则通过将 list 中 Buffer 实例的长度相加来计算。
【If totalLength is not provided, it is calculated from the Buffer instances
in list by adding their lengths.】
如果提供了 totalLength,它会被强制转换为无符号整数。如果 list 中 Buffer 的总长度超过 totalLength,结果将被截断为 totalLength。如果 list 中 Buffer 的总长度小于 totalLength,剩余空间将用零填充。
【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. If the combined length of the Buffers in list is
less than totalLength, the remaining space is filled with zeros.】
import { Buffer } from 'node:buffer';
// 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: 42const { Buffer } = require('node:buffer');
// 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: 42Buffer.concat() 也可能像 Buffer.allocUnsafe() 一样使用内部 Buffer 池。