Created
September 19, 2023 15:54
-
-
Save amir-arad/06232caab577893a6aa04bacee44ec09 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const dataUrlPrefix = "data:application/octet-stream;base64,"; | |
export async function bufferToBase64(buffer: Uint8Array): Promise<string> { | |
const base64url = await new Promise<string>((resolve) => { | |
const reader = new FileReader(); | |
reader.onload = () => resolve(reader.result as string); | |
reader.readAsDataURL(new Blob([buffer])); | |
}); | |
return base64url.slice(dataUrlPrefix.length); | |
} | |
export async function base64ToBuffer(base64: string): Promise<Uint8Array> { | |
const base64url = dataUrlPrefix + base64; | |
const response = await fetch(base64url); | |
const blob = await response.blob(); | |
return new Uint8Array(await blob.arrayBuffer()); | |
} | |
// Test the functions | |
async function test() { | |
const originalBuffer = new Uint8Array([1, 2, 3, 4, 5]); | |
console.log("Original buffer:", originalBuffer); | |
const base64 = await bufferToBase64(originalBuffer); | |
console.log("Base64:", base64); | |
const decodedBuffer = await base64ToBuffer(base64); | |
console.log("Decoded buffer:", decodedBuffer); | |
// Check if the original and decoded buffers are equal | |
const isEqual = | |
originalBuffer.length === decodedBuffer.length && | |
originalBuffer.every((value, index) => value === decodedBuffer[index]); | |
console.log("Buffers are equal:", isEqual); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment