Blob to Base64 in NodeJS without FileReader

Viewed 9710

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?

2 Answers

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.text()); or Buffer.from(await blob.arrayBuffer());.
Note that blob.arrayBuffer() may not be supported yet in your environment.
Here blob.text() can be used, because Buffer.from will use utf8 by default.

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.text());
    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');
}

It's also possible to use Buffer.from(await response.arrayBuffer()) to get a buffer
(in this case Buffer.from is necessary for toString('base64') to work; without it you will get "[object ArrayBuffer]").

Related