Base64 encoding and decoding in client-side Javascript

前端 未结 14 2268
挽巷
挽巷 2020-11-22 04:27

Are there any methods in JavaScript that could be used to encode and decode a string using base64 encoding?

14条回答
  •  执笔经年
    2020-11-22 04:52

    Internet Explorer 10+

    // Define the string
    var string = 'Hello World!';
    
    // Encode the String
    var encodedString = btoa(string);
    console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
    
    // Decode the String
    var decodedString = atob(encodedString);
    console.log(decodedString); // Outputs: "Hello World!"
    

    Cross-Browser

    Re-written and modularized UTF-8 and Base64 Javascript Encoding and Decoding Libraries / Modules for AMD, CommonJS, Nodejs and Browsers. Cross-browser compatible.


    with Node.js

    Here is how you encode normal text to base64 in Node.js:

    //Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter. 
    // Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
    var b = new Buffer('JavaScript');
    // If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
    // We can make it convert to other formats by passing the encoding type to toString().
    var s = b.toString('base64');
    

    And here is how you decode base64 encoded strings:

    var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
    var s = b.toString();
    

    with Dojo.js

    To encode an array of bytes using dojox.encoding.base64:

    var str = dojox.encoding.base64.encode(myByteArray);
    

    To decode a base64-encoded string:

    var bytes = dojox.encoding.base64.decode(str)
    

    bower install angular-base64

    
    
    angular
        .module('myApp', ['base64'])
        .controller('myController', [
    
        '$base64', '$scope', 
        function($base64, $scope) {
        
            $scope.encoded = $base64.encode('a string');
            $scope.decoded = $base64.decode('YSBzdHJpbmc=');
    }]);
    

    But How?

    If you would like to learn more about how base64 is encoded in general, and in JavaScript in-particular, I would recommend this article: Computer science in JavaScript: Base64 encoding

提交回复
热议问题