8

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 3

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

slice() returns a part of buffer by reference! that means both will change if you change one of them.
8

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

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.