Node.js Reference Β· Buffers and Encoding
Node.js Buffer.concat() method
Reference for Buffer.concat() in Node.js: join an array of buffers or Uint8Arrays into one, the totalLength argument, truncation, padding and performance.
Buffer.concat(list) joins an array of buffers (or Uint8Arrays) into one new buffer. The most common use is collecting chunks from a stream: data events deliver pieces, and Buffer.concat(chunks) assembles the complete payload once the stream ends.
The result is always a fresh copy, even when the list has a single element, so changing it never affects the inputs. An optional totalLength lets you cut the result short or pad it with zeros.
const all = Buffer.concat([Buffer.from('ab'), Buffer.from('cd')]); console.log(all.toString()); // 'abcd'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
Buffer.concat(list[, totalLength])
| Name | Description |
|---|---|
list |
An array of Buffer or Uint8Array instances. |
totalLength |
Optional. The length of the result in bytes. Shorter than the sum truncates; longer pads the end with zeros. |
Returns: a new Buffer. For an empty list it is a zero-length buffer.
Errors: ERR_INVALID_ARG_TYPE if list is not an array or an element is not a Buffer or Uint8Array (strings, numbers and arrays are not accepted). ERR_OUT_OF_RANGE if totalLength is negative.
Usage notes
- Passing
totalLengthskips the pass that sums the lengths. It is a minor speedup, but a wrong value silently truncates or pads, so only pass it when you know it. - Do not grow a buffer by calling
Buffer.concat()repeatedly in a loop: every call copies everything so far, which makes the loop quadratic. Collect pieces in an array and concatenate once. - Decode text after concatenating. Decoding each chunk separately breaks multi-byte characters that straddle a chunk boundary, as the second example shows;
StringDecoderor streamsetEncoding()handle this. - Zero-padding with
totalLengthis the one case where a buffer fromconcat()contains bytes you did not supply (zeros). - Large buffers from
concat()are allocated without the shared pool, while small ones may use it, as withBuffer.from(). - For an array of strings, use
Array.prototype.join()instead;concat()only handles bytes.
Related
- Buffer.from()
- Buffer.alloc()
- buf.copy()
- Buffer
- Tutorial: Buffers