Search code examples
iosparse-platformparse-cloud-code

Base64 encode a string in Cloud Code


How do I base64 encode a string in cloud code? The value is for a HTTP Basic Auth.

I have tried the following two approaches and I had no success.

var string = 'AQXTTPmj-boT_yDEPQXg9ezIOIM7O:EMx6RLr8jF3S6YYo-X4bZ';
var buffer1 = new Buffer(string, 'base64');
var b3 = buffer1.toString('base64');
console.log(b3);

var string = 'AQXTTPmj-boT_yDEPQXg9ezIOIM7O:EMx6RLr8jF3S6YYo-X4bZ';
var encodeString = Base64.encode(string);
console.log(encodeString);

Solution

  • You send your string to the Buffer constructor and use toString method to convert it to base64 like this:

    var string = 'AQXTTPmj-boT_yDEPQXg9ezIOIM7O:EMx6RLr8jF3S6YYo-X4bZ';
    var buffer1 = new Buffer(string);
    var b3 = buffer1.toString('base64');
    console.log(b3);
    

    Also make sure you put var Buffer = require('buffer').Buffer; on top of your main.js file.