Skip to content
Related Articles
Open in App
Not now

Related Articles

Node.js Buffer.copy() Method

Improve Article
Save Article
  • Last Updated : 13 Oct, 2021
Improve Article
Save Article

Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like an array of integers.

The Buffer.copy() method simply copies all the values from input buffer to another buffer.


buffer.copy( target, targetStart, sourceStart, sourceEnd )

Parameters: This method accept two parameters as mentioned above and described below:

  • target: It is a buffer in which you need to copy all the values.
  • targetStart: It refers to the starting index from which the elements of target buffer will begin writing. Its default value is 0.
  • sourceStart: It is the index of input buffer from which the copying of values will start. Its default value is 0.
  • sourceEnd: The index of input buffer till which the copying of values will be done. Its default value is buffer.length size.

Return Value: This method returns the number that indicates the number of bytes copied.

Note: Copies the values from input buffer and overwrites them to output buffer even if the target memory regions (indexes) already exist. Copies data from a region of input buffer to a region in target buffer even if the target memory region overlaps with input buffer.

Below examples illustrate the use of Buffer.includes() Method in Node.js:

Example 1:

// Node.js program to demonstrate the  
// Buffer.copy() Method 
// Creating a buffer
var buffer2 = Buffer.from('for');
var buffer1 = Buffer.from('GeeksandGeeks');
buffer2.copy(buffer1, 5, 0);



Example 2:

// Node.js program to demonstrate the  
// Buffer.copy() Method
var buffer2 = Buffer.allocUnsafe(5);
var buffer1 = Buffer.from('Geeks');
for (let i = 0; i < 5; i++) {
    // Adds: 'a b c d e' as 97 98 99 100 101
    // are their respective ASCII values
    buffer2[i] = i + 97;
buffer2.copy(buffer1, 2);
// Prints 'Geabc' as the input buffer1
// carries 'Geeks' and we provided the
// targetStart index as 2
// so elements will replace the values in
// buffer1 starting from index 2



Note: The above program will compile and run by using the node index.js command.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!