copy()
in Node.js
?The copy()
method of the Buffer
class in Node.js
copies data from a Buffer
object to another Buffer
object.
The data is copied regardless of whether the memory regions of the Buffer
objects overlap.
The process is illustrated below.
The prototype of the copy()
method is shown below.
buf.copy(target, targetStart, sourceStart, sourceEnd);
The keyword
buf
represents anyBuffer
object inNode.js
.
The copy()
method accepts the following parameters:
target
: The Buffer
object into which the data is to be copied.
targetStart
: The offset of the destination Buffer
from which to start writing data. By default, this parameter has a value of .
sourceStart
: The offset of source buffer buf
from which to start copying data. By default, this parameter has a value of .
sourceEnd
: The offset of source buffer buf
from which to stop copying data. By default, this parameter is equal to the length of buf
.
The copy()
method returns an integer that represents the number of copied bytes.
The code below shows how the copy()
method can be used in Node.js
.
// initialize buffer objectsvar bufferOne = Buffer.from('World');var bufferTwo = Buffer.from('Hello');var bufferThree = Buffer.from('Buffers');var bufferFour = Buffer.from('Learning Node.js with Educative');// copy bufferOne to bufferTwoconsole.log("Before calling copy(), bufferTwo is: ", bufferTwo.toString())var bytes = bufferOne.copy(bufferTwo)console.log("After calling copy(), bufferTwo is: ", bufferTwo.toString())console.log("Copied", bytes, "bytes.\n");// copy subset of bufferThree to bufferFourconsole.log("Before calling copy(), bufferFour is: ", bufferFour.toString())bytes = bufferThree.copy(bufferFour, 9);console.log("After calling copy(), bufferFour is: ", bufferFour.toString())console.log("Copied", bytes, "bytes");
First, we initialize multiple Buffer
objects through the from()
method. Each Buffer
has a unique value.
The copy()
method in line copies all of bufferOne
into bufferTwo
. Since no values are provided for the targetStart
, sourceStart
, and sourceEnd
parameters, the copy()
method takes their default values as , , and , respectively.
Similarly, the copy()
method in line copies all of bufferThree
into bufferFour
, starting at the specified offset, i.e., index of bufferFour
.
Since bufferThree
contains characters, indices are overwritten in bufferFour
. Originally, these indices contained the characters Node.js
, but after the copy()
method is invoked, the characters from bufferThree
are copied into these indices.
For more details about the
Buffer
class inNode.js
, please check the documentation.