I currently have a blob of type 'image/jpeg' that I need to convert to a base64 string. All my code is in a independent javascript file using Nodejs and is not connected with any html files. Every method I have looked into to turn the blob into base64 involves using the FileReader class which requires the javascript to be within html, so that is out of the question. The only other work around I found was to convert the blob into a buffer then to base64 using this line of code.
base64 = new Buffer( blob, 'binary').toString('base64');
But this only returns the error: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
I am quite stumped... any suggestions?
If you are reading from a URL with node-fetch in NodeJS, you don't want to get a blob but rather a buffer. You can then easily convert to base64.
const b64 = await fetch(url)
.then((response) => response.buffer())
.then((buffer) => {
const b64 = buffer.toString('base64');
return b64;
})
.catch(console.error);
For NodeJS (with node-fetch), you can get a buffer from blob using Buffer.from(await blob.arrayBuffer());.
However, you don't need to get a blob from node-fetch.
You can just get a buffer directly from the response.
And the info from blob.type can be obtained from the response header.
For example, to get a data url, using blob:
async function toDataURL_node(url) {
let response = await fetch(url);
let blob = await response.blob();
let buffer = Buffer.from(await blob.arrayBuffer());
return "data:" + blob.type + ';base64,' + buffer.toString('base64');
}
And without using blob:
async function toDataURL_node(url) {
let response = await fetch(url);
let contentType = response.headers.get("Content-Type");
let buffer = await response.buffer();
return "data:" + contentType + ';base64,' + buffer.toString('base64');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With