An important part of working with buffers is the ability to copy data from one buffer into another buffer. Node.js provides the copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])
function for Buffer
objects. The targetBuffer
parameter is another Buffer
object, and targetStart
, sourceStart
and sourceEnd
are indexes inside the source and target buffers.
To copy string data from one buffer to another, make sure that both buffers use the same encoding, or you may get unexpected results when decoding the resulting buffer.
You can also copy data from one buffer to the other by indexing them directly, as in this example:
sourceBuffer[index] = destinationBuffer[index]
The code in Listing 5.3 illustrates three examples of copying data from one buffer to another. The first method, in lines 4–8, copies the full buffer. The next method, in lines 10–14, copies only the middle 5 bytes of a buffer. The third example, in lines 15–22, iterates through the source buffer and copies only every other byte in the buffer. Figure 5.3 shows the results.
Listing 5.3 buffer_copy.js
: Various ways to copy data from one Buffer
object to another
01 var alphabet = new Buffer('abcdefghijklmnopqrstuvwxyz'),
02 console.log(alphabet.toString());
03 // copy full buffer
04 var blank = new Buffer(26);
05 blank.fill();
06 console.log("Blank: " + blank.toString());
07 alphabet.copy(blank);
08 console.log("Blank: " + blank.toString());
09 // copy part of buffer
10 var dashes = new Buffer(26);
11 dashes.fill('-'),
12 console.log("Dashes: " + dashes.toString());
13 alphabet.copy(dashes, 10, 10, 15);
14 console.log("Dashes: " + dashes.toString());
15 // copy to and from direct indexes of buffers
16 var dots = new Buffer('-------------------------'),
17 dots.fill('.'),
18 console.log("dots: " + dots.toString());
19 for (var i=0; i < dots.length; i++){
20 if (i % 2) { dots[i] = alphabet[i]; }
21 }
22 console.log("dots: " + dots.toString());
3.21.247.16