Modern frontend deveolpment increasingly requires handling binary data through various web APIs. This article explores key JavaScript APIs for binary operations.
Base64 Encoding Utilities
The atob() and btoa() functions handle Base64 encoding/decoding of ASCII strings:
btoa('A') // Returns "QQ=="
Base64 encoding follows these steps:
- Convert character to 8-bit binary
- Pad to 24-bit chunks
- Split into 6-bit segments
- Map to Base64 character set
Character Encoding Considerations
Special characters require UTF-8 handling:
'😂'.charCodeAt(0).toString(16) // Returns "d83d"
'😂'.charCodeAt(1).toString(16) // Returns "de02"
File API Operations
Working with files in the browser:
// Create File instance
const file = new File(['content'], 'example.txt')
// Read file as ArrayBuffer
const reader = new FileReader()
reader.onload = e => console.log(e.target.result)
reader.readAsArrayBuffer(file)
Binary Data Conversion
Convert between different binary formats:
// Base64 to File
function base64ToFile(dataUrl, filename) {
const arr = dataUrl.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
const u8arr = new Uint8Array(bstr.length)
for (let i = 0; i < bstr.length; i++) {
u8arr[i] = bstr.charCodeAt(i)
}
return new File([u8arr], filename, {type: mime})
}
Typed Arrays
JavaScript provides several typed array views for binary data:
// Different element sizes
new Int8Array() // 1-byte elements
new Int16Array() // 2-byte elements
new Uint32Array() // 4-byte elements
Network Operations
Fetch API handles binary responses:
fetch('/image.png')
.then(res => res.blob())
.then(blob => {
const imgUrl = URL.createObjectURL(blob)
document.getElementById('img').src = imgUrl
})
Canvas Binary Output
Canvas provides binary export methods:
// Synchronous data URL
const dataUrl = canvas.toDataURL('image/png')
// Asynchronous blob
canvas.toBlob(blob => {
console.log(blob)
}, 'image/jpeg', 0.95)
Web Workers
Binary data transfers efficiently to workers:
// Main thread
const worker = new Worker('worker.js')
worker.postMessage(binaryData)
// Worker thread
onmessage = e => {
const data = e.data
// Process binary data
}