Concatenating Buffers

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.

Listing 5.5 buffer_concat.js: Concatenating Buffer objects


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());


Image

Figure 5.5 Output of buffer_concat.js, concatenating Buffer objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.186.202