I want to know what is the use of buffer.copy() in nodejs application. Please explain with any real time example? And also the difference between the copy and slice methods in node js. How it works?
I want to know what is the use of buffer.copy() in nodejs application. Please explain with any real time example? And also the difference between the copy and slice methods in node js. How it works?
Share Improve this question edited Feb 13, 2017 at 14:15 555 1579 bronze badges asked Feb 13, 2017 at 13:17 saiibittasaiibitta 4071 gold badge3 silver badges18 bronze badges3 Answers
Reset to default 10Unlike strings, buffers in Node are mutable. It means that you can create a buffer, pass it somewhere else and when it is changed in one place it will change in both places which is not always what you want. If you want to make sure that nothing can change your buffer then you need to copy it.
The slice()
returns a new buffer that is a part of the old one, similarly to how slice()
works for strings or arrays.
buffer.copy() copies a buffer. here is an example
var buffer1 = new Buffer('ABC');
//copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());
When the above program is executed, it produces the following result −
buffer2 content: ABC
buffer.slice() method is used to get a sub-buffer of a node buffer − Here is the example.
var buffer1 = new Buffer('maximizedPoint');
//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());
When the above program is executed, it produces the following result −
buffer2 content: maximized
The modern version to clone a Buffer without mutating the other is using Buffer.from()
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: buffer