Base64 encoding and decoding in client-side Javascript

前端 未结 14 2257
挽巷
挽巷 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:56

    For what it's worth, I got inspired by the other answers and wrote a small utility which calls the platform specific APIs to be used universally from either Node.js or a browser:

    /**
     * Encode a string of text as base64
     *
     * @param data The string of text.
     * @returns The base64 encoded string.
     */
    function encodeBase64(data: string) {
        if (typeof btoa === "function") {
            return btoa(data);
        } else if (typeof Buffer === "function") {
            return Buffer.from(data, "utf-8").toString("base64");
        } else {
            throw new Error("Failed to determine the platform specific encoder");
        }
    }
    
    /**
     * Decode a string of base64 as text
     *
     * @param data The string of base64 encoded text
     * @returns The decoded text.
     */
    function decodeBase64(data: string) {
        if (typeof atob === "function") {
            return atob(data);
        } else if (typeof Buffer === "function") {
            return Buffer.from(data, "base64").toString("utf-8");
        } else {
            throw new Error("Failed to determine the platform specific decoder");
        }
    }

提交回复
热议问题