What is the Buffer.copy() method in Node.js?
What is 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.
Syntax
The prototype of the copy() method is shown below.
buf.copy(target, targetStart, sourceStart, sourceEnd);
The keyword
bufrepresents anyBufferobject inNode.js.
Parameters
The copy() method accepts the following parameters:
-
target: TheBufferobject into which the data is to be copied. -
targetStart: The offset of the destinationBufferfrom which to start writing data. By default, this parameter has a value of . -
sourceStart: The offset of source bufferbuffrom which to start copying data. By default, this parameter has a value of . -
sourceEnd: The offset of source bufferbuffrom which to stop copying data. By default, this parameter is equal to the length ofbuf.
Return value
The copy() method returns an integer that represents the number of copied bytes.
Code
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");
Explanation
-
First, we initialize multiple
Bufferobjects through thefrom()method. EachBufferhas a unique value. -
The
copy()method in line copies all ofbufferOneintobufferTwo. Since no values are provided for thetargetStart,sourceStart, andsourceEndparameters, thecopy()method takes their default values as , , and , respectively. -
Similarly, the
copy()method in line copies all ofbufferThreeintobufferFour, starting at the specified offset, i.e., index ofbufferFour. -
Since
bufferThreecontains characters, indices are overwritten inbufferFour. Originally, these indices contained the charactersNode.js, but after thecopy()method is invoked, the characters frombufferThreeare copied into these indices.
For more details about the
Bufferclass inNode.js, please check the documentation.