Buffer is a temporary memory storage that 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 the input buffer to another buffer.
Syntax:
buffer.copy( target, targetStart, sourceStart, sourceEnd )
Parameters: This method accepts 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 the target buffer will begin writing. Its default value is 0.
- sourceStart: It is the index of the 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 a buffer.length size.
Return Value: This method returns the number that indicates the number of bytes copied.
Note: Copies the values from the input buffer and overwrites them to the output buffer even if the target memory regions (indexes) already exist. Copies data from a region of the input buffer to a region in the target buffer even if the target memory region overlaps with the input buffer.
Example 1: The below example illustrates the use of Buffer.includes() Method in Node.js
javascript
let buffer2 = Buffer.from( 'for' );
let buffer1 = Buffer.from( 'GeeksandGeeks' );
buffer2.copy(buffer1, 5, 0);
console.log(buffer1.toString());
|
Output:
GeeksforGeeks
Example 2: The below example illustrates the use of Buffer.includes() Method in Node.js
javascript
let buffer2 = Buffer.allocUnsafe(5);
let buffer1 = Buffer.from( 'Geeks' );
for (let i = 0; i < 5; i++) {
buffer2[i] = i + 97;
}
buffer2.copy(buffer1, 2);
console.log(buffer1.toString());
|
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Apr, 2023
Like Article
Save Article