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?
3 Answers
Unlike 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.
1 Comment
slice() returns a part of buffer by reference! that means both will change if you change one of them.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