4

Have this module.exports file which fetches an image from an API endpoint. The API result is then parsed into a blob. After parsing the Blob object looks like this:

Blob {
  [Symbol(type)]: 'image/jpeg',
  [Symbol(buffer)]:
   <Buffer ff d8 ff db 00 43 00 08 06 06 07 06 05 08 07 07 07 09 09 08 0a 0c 14
0d 0c 0b 0b 0c 19 12 13 0f 14 1d 1a 1f 1e 1d 1a 1c 1c 20 24 2e 27 20 22 2c 23 1c
 ... > }

And here's the code:

// Pre Configuration
const fetch = require('node-fetch')

module.exports = async (req, res, photoKey) => {
    let photoUrl = null
    const apiURL = "https://media.heartenly.com/stg/CACHE/sc_thumb"
    const requestURL = `${apiURL}/${photoKey}`
    const response = await fetch(requestURL)
    const data = await response.blob()
    console.log(data)
}      

Now what I want to do is to return base64 URL format of the returned blob, any ideas?

4
  • data.toString('base64')? or perhaps data.buffer.toString('base64') - I'm not familiar with blobs in nodejs Commented Sep 30, 2018 at 10:24
  • here is a good answer: stackoverflow.com/questions/18650168/convert-blob-to-base64
    – Nezir
    Commented Sep 30, 2018 at 10:26
  • @Nezir - that's not nodejs Commented Sep 30, 2018 at 10:26
  • though, it's probably more like const data = await response.buffer(); console.log(data.toString('base64')) - because the Blob buffer seems to be hard to get at Commented Sep 30, 2018 at 10:32

2 Answers 2

12

Looking at node-fetch, it looks impossible to get at the Blob buffer, so, the best bet is to do the following

  1. use response.buffer instead of response.blob
  2. use toString('base64') to get the data in base64

in other words:

const fetch = require('node-fetch');

module.exports = async (req, res, photoKey) => {
    let photoUrl = null;
    const apiURL = "https://media.heartenly.com/stg/CACHE/sc_thumb";
    const requestURL = `${apiURL}/${photoKey}`;
    const response = await fetch(requestURL);
    const data = await response.buffer()
    const b64 = data.toString('base64');
    console.log(b64);
}; 
0

As the fetch API in Node has now reached experimental support (default enabled) (Node 18) this can now be achieved without the help of an external library:

module.exports = async (req, res, photoKey) => {
    let photoUrl = null
    const apiURL = "https://media.heartenly.com/stg/CACHE/sc_thumb"
    const requestURL = `${apiURL}/${photoKey}`
    const response = await fetch(requestURL)
    const buffer = await response.arrayBuffer();
    const base64 = Buffer.from(buffer).toString('base64');
    console.log(data)
} 

The difference here is that the response is not parsed to a blob but to an arrayBuffer. You may also want to use this approach because the response.buffer() method of node-fetch is depreciated

Not the answer you're looking for? Browse other questions tagged or ask your own question.