1

I'm trying to get the value (which is a binary data of an image) inside the body of a promise that looks like this. And is there a way to turn the binary data into a base64 encode?

"Promise"{
"IncomingMessage"{
    "_readableState":"ReadableState"{...
    },
    "readable":false,
    "_events":[...
    ]{...
    },
    "_eventsCount":4,
    "_maxListeners":"undefined",
    "socket":"TLSSocket"{...
    },
    "connection":"TLSSocket"{...
    },
    "httpVersionMajor":1,
    "httpVersionMinor":1,
    "httpVersion":"1.1",
    "complete":true,
    "headers":{...
    },
    "rawHeaders":[...
    ],
    "trailers":{...
    },
    "rawTrailers":[...
    ],
    "aborted":false,
    "upgrade":false,
    "url":"",
    "method":null,
    "statusCode":200,
    "statusMessage":"OK",
    "client":"TLSSocket"{...
    },
    "_consuming":true,
    "_dumped":false,
    "req":"ClientRequest"{...
    },
    "request":"Request"{...
    },
    "toJSON":[...
    ],
    "caseless":"Caseless"{...
    },
    "body": //binary values here

Now, the code to access them is by console.log(getto) inside an async function

async function getMedia(imgMsgUrl, auth) {
const getImage = {
    url: imgMsgUrl,
    oauth: auth,
};
var getto = get(getImage);
await getto;
console.log(getto);
};

How do I easily access the body by modifying the code inside the async function? And how do I turn it into a base64 encode?

nawhki
  • 57
  • 6
  • Does this answer your question? [How to do Base64 encoding in node.js?](https://stackoverflow.com/questions/6182315/how-to-do-base64-encoding-in-node-js) – Nishant Bhatia Aug 27 '20 at 16:20
  • No, it doesn't. Because I'm trying to access the value of the "body" first, and I don't know how, then it will be converted into base64 later. Thank you for the suggestion. – nawhki Aug 27 '20 at 16:28

2 Answers2

2

I got it to work. Here's the code.

async function getMedia(imgMsgUrl, auth) {
const getImage = {
    url: imgMsgUrl,
    oauth: auth,
};
var getto = get(getImage).then(function(response) {
    let buffer = Buffer.from(response.body);
    let base64 = buffer.toString('base64');
    console.log(base64);
});
await getto;
};
nawhki
  • 57
  • 6
1

Since it the result of get(getImage) is a promise, you can't access the value like you will access a variable. You can only get the result in an async function using await (like you did above) or perform whatever action you want with it in a callback function passed to Promise.then()

function getMedia(imgMsgUrl, auth) {
  const getImage = {   
    url: imgMsgUrl,
    oauth: auth,
  };
  var getto = get(getImage);
  getto.then(result => {
    doSomething(result)
  });
};
FarayolaJ
  • 31
  • 3