a shot of dev knowledge

RELATED TAGS

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 buf represents any Buffer object in Node.js.

Parameters

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 00.

  • sourceStart: The offset of source buffer buf from which to start copying data. By default, this parameter has a value of 00.

  • sourceEnd: The offset of source buffer buf from which to stop copying data. By default, this parameter is equal to the length of buf.

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 objects
var 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 bufferTwo
console.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 bufferFour
console.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 Buffer objects through the from() method. Each Buffer has a unique value.

  • The copy() method in line 1010 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 00, 00, and 55, respectively.

  • Similarly, the copy() method in line 1515 copies all of bufferThree into bufferFour, starting at the specified offset, i.e., index 99 of bufferFour.

  • Since bufferThree contains 66 characters, indices 9159-15 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 in Node.js, please check the documentation.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring