Files
nms/libs/base64.js

27 lines
898 B
JavaScript

// Base64 UTF-8 Encode/Decode Utility Functions
// Source: https://www.digitalocean.com/community/tutorials/how-to-encode-and-decode-strings-with-base64-in-javascript
module.exports = {
// Function to encode a UTF-8 string to Base64
utf8ToBase64: (str) => {
const encoder = new TextEncoder()
const data = encoder.encode(str)
const binaryString = String.fromCharCode.apply(null, data)
return btoa(binaryString)
},
// Function to decode a Base64 string to UTF-8
base64ToUtf8: (b64) => {
const binaryString = atob(b64)
// Create a Uint8Array from the binary string.
const bytes = new Uint8Array(binaryString.length)
for (let i = 0 ; i < binaryString.length ; i++) {
bytes[i] = binaryString.charCodeAt(i)
}
const decoder = new TextDecoder()
return decoder.decode(bytes)
}
}