Node.js | Buffer.copy() Method

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.

Syntax:



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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
  
console.log(buffer1.toString());

chevron_right


Output:

GeeksforGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
  
console.log(buffer1.toString());

chevron_right


Output:

Geabc

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

Reference: https://nodejs.org/api/buffer.html#buffer_buf_copy_target_targetstart_sourcestart_sourceend



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.