Reputation: 55739
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
Upvotes: 0
Views: 353
Reputation: 48240
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
Upvotes: 2