Search code examples
javascriptnode.jsbase64deployd

How can I Base64 encode a string in a Deployd event script?


I'm using Deployd to build an API to be consumed by an AngularJS app. I'm attempting to integrate the ng-s3upload module to save some images on Amazon S3. The ng-s3upload module requires the backend server, in this case deployd, to generate a Base64 encoded policy. I created a GET event to generate the policy but haven't figured out how I can Base64 encode it form within the Deployd event script. Any help or ideas is appreciated. I tried to use the NodeJS Buffer function, Deployd is based on Node, but it is not available form the event script environment.


Solution

  • You can use the btoa() function to encode strings to base64 format.

    var encodedStr = btoa(originalString);
    

    EDITED As you say you can't use btoa, I wrote an implementation of a base64 encoding function. You use it just like this:

    var base64str = str.toBase64();
    

    Here is the code, you can see it in action in this jsfiddle.

    var code = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
                'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', '+', '/'];
    
    String.prototype.padLeft = function(desiredLength, padChar) {
        if (this.length >= desiredLength) return this; 
        var count = desiredLength - this.length;
        var result = '';
        while(count--)
            result += padChar;
        return result + this;
    };
    
    function getBinaryString(str) {
        var binaryStr = '';
        for (var i = 0; i < str.length; i++) {
            binaryStr += str.charCodeAt(i).toString(2).padLeft(8, '0');
        }
        return binaryStr;
    }
    
    function getBase64FromBinaryString(binaryStr) {
        var padRightCount = binaryStr.length % 3;
        var numChars = binaryStr.length / 6;
        var maxChars = numChars - padRightCount;
        while (padRightCount--) binaryStr += '00000000';
    
        var result = '';
        for (var i = 0; i < numChars; i++) {
            var pos = i * 6;
            result += code[parseInt(binaryStr.substr(pos, 6), 2)];
        }
    
        for (var i = 0; i < (numChars - maxChars); i++)
            result += '=';
    
        return result;
    }
    
    String.prototype.toBase64 = function() {
        var binaryStr = getBinaryString(this);
        return getBase64FromBinaryString(binaryStr);
    }