Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buffer from ArrayBuffer with memory copy

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)
like image 812
Nico AD Avatar asked Jun 16 '26 02:06

Nico AD


1 Answers

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.

like image 181
mihai Avatar answered Jun 18 '26 01:06

mihai