4

I'm switching from Node.js 8.X to Node.js 10.x and I'm getting some deprecated warnings on "new Buffer"

I have an arrayBuffer that I need to copy into a Buffer and my first version was like this:

const newBuffer = Buffer.from(myArrayBuffer)

But the arrayBuffer is not copied in this case ( https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length ) so my data was corrupted in some cases when I refer to the buffer in asychronous code

so I switched to :

const newBuffer = new Buffer(Buffer.from(myArrayBuffer))

it works, but I get a warning with Node.js 10.X

I made this , but not sure it's the best way to achieve this

const newBuffer = Buffer.alloc(myArrayBuffer.byteLength)
const abView = Buffer.from(myArrayBuffer)
abView.copy(newBuffer)
1
  • Could you please post your solution as answer so that everyone can easily see it? Commented Sep 21, 2021 at 14:41

1 Answer 1

1

To be on the safe side, you could do a byte by byte copy using a plain old for loop:

var newBuffer = new Buffer.alloc(myArrayBuffer.byteLength)

for (var i = 0; i < myArrayBuffer.length; i++)
    newBuffer[i] = myArrayBuffer[i];

This way you are sure to be dealing with a new object and not just a view on the ArrayBuffer.

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.