@ricsam/quickjs-encoding
v0.2.17
Published
Base64 encoding APIs (atob, btoa) for QuickJS runtime
Downloads
1,627
Maintainers
Readme
@ricsam/quickjs-encoding
Base64 encoding APIs (atob, btoa) for QuickJS runtime.
Note: This is a low-level package. For most use cases, use
@ricsam/quickjs-runtimewithcreateRuntime()instead.
Installation
bun add @ricsam/quickjs-encodingSetup
import { setupEncoding } from "@ricsam/quickjs-encoding";
const handle = setupEncoding(context);Injected Globals
atob(encodedData)- Decode a Base64-encoded stringbtoa(stringToEncode)- Encode a string to Base64
Usage in QuickJS
// Encode string to Base64
const encoded = btoa("Hello, World!");
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="
// Decode Base64 to string
const decoded = atob("SGVsbG8sIFdvcmxkIQ==");
console.log(decoded); // "Hello, World!"
// Common use case: encoding JSON for transport
const data = { user: "john", token: "abc123" };
const base64Data = btoa(JSON.stringify(data));
// Decode it back
const originalData = JSON.parse(atob(base64Data));Error Handling
// btoa throws for characters outside Latin1 range (0-255)
try {
btoa("Hello 世界"); // Throws DOMException
} catch (e) {
console.error("Cannot encode non-Latin1 characters");
}
// atob throws for invalid Base64
try {
atob("not valid base64!!!");
} catch (e) {
console.error("Invalid Base64 string");
}