1
votes

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?

1
How do you obtain the blob file ? Can't you simply open the file with fs ? - TGrif
I used the Fetch API to turn an html link of a .jpg (ex. i.imgur.com/Aj19ba2.jpg ) into a blob. The exact code is this: fetch(image , {mode: 'no-cors'}) .then( response => response.blob()) .then(blob => { console.log(blob); }); - JC Sergent
@JCSergent Did you ever solve this problem? I am doing something similar but held back by not having FileReader - sbatson5
answered to @TGrif, blob obtain from BD Oracle ¿Any solution, I'm stuck here too? - user3445492

1 Answers

6
votes

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);