0

The following modifies a slice of a Buffer.

In doing so, it modifies the original Buffer too. If I were to perform a similar operation on an Array, then the original would remain unchanged.

So is this behavior the result of the specific implementation of the slice method on Node.js' Buffer?

const fs = require('fs');

fs.readFile(__filename, (err, buffer) => {
  const tag = buffer.slice(-2, -1);
  tag[0] = 'B';

  console.log(buffer.toString());
});

 // TAG: A

1 Answer 1

2

The docs says

Returns a new Buffer that references the same memory as the original, but offset and cropped by the start and end indices. Note: Modifying the new Buffer slice will modify the memory in the original Buffer because the allocated memory of the two objects overlap.

https://nodejs.org/api/buffer.html#buffer_buf_slice_start_end

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

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.