You can concatenate two or more Buffer
objects together to form a new buffer. The concat(list, [totalLength])
method accepts an array of Buffer
objects as the first parameter and totalLength
, defining the maximum bytes in the buffer, as an optional second argument. The Buffer
objects are concatenated in the order in which they appear in the list, and a new Buffer
object is returned, containing the contents of the original buffers up to totalLength
bytes.
If you do not provide a totalLength
parameter, concat()
figures out the total length for you. However, it has to iterate through the list, so providing a totalLength
value is a bit faster.
The code in Listing 5.5 illustrates concatenation by concatenating a base Buffer
object with one buffer and then another. Figure 5.5 shows the output.
1 var af = new Buffer("African Swallow?");
2 var eu = new Buffer("European Swallow?");
3 var question = new Buffer("Air Speed Velocity of an ");
4 console.log(Buffer.concat([question, af]).toString());
5 console.log(Buffer.concat([question, eu]).toString());
3.142.171.253