How to convert Buffer data type to Base64 in JavaScript Node.js

Viewed 2495

I have this code for Models:

// ...
var account = {
    picture: function(account_id, callback) {
        return db.query("SELECT image_profile FROM account_info WHERE account_info_id=?", [account_id], callback);
    }
};
//...

And this is for Router:

// ...
router.post('/picture/:id?', function(req, res, next) {
    account.picture(req.params.id, function(err, rows) {
        if (err) {
            res.json({ 'success': false });
        } else {
            res.json(rows);
        }
    });
});
// ...

So the output JSON format like this:

[
  {
    "image_profile": {
      "type": "Buffer",
      "data": [
        255,
        216,
        255,
        224,
        0,// ... too long cause this is BLOB file from database

How can I convert that "data" on JSON to Base64?

1 Answers

I used this code and it worked:

let str = ""
bufferArray.forEach(function(index) {
    str += String.fromCharCode(index)
})
console.log(str)

In your code "data": [255,216,255,224,0,..] is bufferArray

You can use btoa(str) to Encode

Related