Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js convert buffer to Int8Array

in the client side, i am converting a TypedArray into Blob and transmitting to server, to check if data is correct, i want to compare the first five values on client side and server side,

on client side:

var fileReader = new FileReader();
fileReader.onload = function() {
    callback(new Int8Array(this.result));
};
fileReader.readAsArrayBuffer(blob);

(from which i read first five values in callback fn)

but on server, I found code to convert blob to buffer, and from my understanding, buffer and arraybuffer are not the same, var buffer1 = new Buffer( blob, 'binary' );

does buffer have something similar to DataView of arraybuffer, now how do I read the first 5 values of buffer1 as integers which I am able to do in client side?

like image 284
mido Avatar asked Aug 25 '26 17:08

mido


2 Answers

To answer the original question, you can use the buffer property of a Buffer instance to get the ArrayBuffer, then instantiate a Uint8Array based on that.

function viewBufferAsUint8Array(buf) {
    return new Uint8Array(buf.buffer);
}

NOTE: The Uint8Array and ArrayBuffer will occupy the same memory, so changes to one will result in changes to the other. The code below will copy the contents into a new Uint8Array that is not linked to the buffer:

function copyBufferToSeparateUint8Array(buf, truncateSizeTo) {
    var orig = new Uint8Array( buf.buffer );
    if (!truncateSizeTo) return new Uint8Array( orig );
    
    var copy = new Uint8Array( truncateSizeTo );
    copy.set( orig );
    return copy;
}

Although copying the buffer into a separate Uint8Array is a little slower, it has the added benefit of allowing one to choose the size of the new Uint8Array.

Example usage:

var buf = Buffer.alloc(4);
buf[0] = buf[1] = buf[2] = buf[3] = 45;

var asU8Array = viewBufferAsUint8Array( buf );

var copiedU8 = copyBufferToSeparateUint8Array( buf );

asU8Array[2] = 120;

console.log( buf[2] );       // 120
console.log( asU8Array[2] ); // 120
console.log( copiedU8[2] );  // 45
like image 198
Jack G Avatar answered Aug 27 '26 07:08

Jack G


Node Buffer is currently entirely based on Uint8Array. Everything you can do with a Uint8Array instance you can do with a Buffer instance. And even more, because Buffer adds additional functions and properties. Internally, when a Buffer instance has to be created, they actually create an Uint8Array instance and then set its prototype to the Node Buffer prototype. So you can access the underlying ArrayBuffer with buffer1.buffer, etc.

like image 33
Viruslav Avatar answered Aug 27 '26 08:08

Viruslav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!