In a react native project i have a HTTP request that returns a binary file that i need to turn into a NodeJS Buffer object. I cannot for the life of me get this to work because arrayBuffer
is not implemented in any form in react native and every single thing out there seems to hinge on that being present.
How can i turn a fetch response into a ANYTHING that can be accepted by Buffer? uint8array, anything.
async getFirmwareDownload(firmwareVersion: FirmwareVersion): Promise<Buffer | null> {
try {
const response = await fetch(`${this.getBaseUrl()}${firmwareVersion.url}`);
const blob = await response.blob();
return Buffer.from(blob);
} catch (err) {
console.error(err);
return null;
}
}
I attempted this and while its not throwing errors trying to convert. It is not converting correctly as it is missing several hundred bytes.
async getFirmwareDownload(firmwareVersion: FirmwareVersion): Promise<Buffer | null> {
try {
const response = await fetch(`${this.getBaseUrl()}${firmwareVersion.url}`);
const text = await response.text();
return Buffer.from(text, 'binary');
} catch (err) {
console.error(err);
return null;
}
}
I was finally able to do it in a VERY roundabout way by converting it to base64 data URL and then back into a Buffer. This is probably horribly inefficient but it at least generates the correct size Buffer that matches the file.
function blobToBuffer(blob: Blob): Promise<Buffer> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = () => {
const data = reader.result.slice(reader.result.indexOf('base64,') + 7);
resolve(Buffer.from(data, 'base64'));
};
reader.readAsDataURL(blob);
});
}
I would greatly appreciate any other method of doing this.