JavaScript में Base64 — btoa() & Buffer
मुफ़्त Base64 Encode Online को सीधे अपने ब्राउज़र में उपयोग करें — इंस्टॉलेशन की ज़रूरत नहीं।
Base64 Encode Online ऑनलाइन आज़माएं →जब आप CSS data URI में कोई इमेज एम्बेड करते हैं, HTTP Authorization हेडर में क्रेडेंशियल पास करते हैं, या किसी बाइनरी सर्टिफिकेट को एनवायरनमेंट वेरिएबल में स्टोर करते हैं, तो आपको ब्राउज़र और Node.js दोनों में JavaScript डेटा को Base64 एनकोड करना होता है। JavaScript दो अलग बिल्ट-इन API प्रदान करता है:btoa() ब्राउज़र वातावरण के लिए (Node.js 16+ में भी उपलब्ध) और Buffer.from() Node.js के लिए — प्रत्येक में Unicode, बाइनरी डेटा और URL सुरक्षा के आसपास अलग-अलग प्रतिबंध हैं। बिना कोई कोड लिखे त्वरित एनकोडिंग के लिए, ToolDeck का Base64 Encoder इसे ब्राउज़र में तुरंत संभालता है। यह गाइड दोनों वातावरणों को प्रोडक्शन-रेडी उदाहरणों के साथ कवर करती है: Unicode हैंडलिंग, URL-safe वेरिएंट, फ़ाइल और API रेस्पॉन्स एनकोडिंग, CLI उपयोग, और वे चार गलतियाँ जो वास्तविक कोडबेस में लगातार बग पैदा करती हैं।
- ✓btoa() ब्राउज़र में नेटिव रूप से उपलब्ध है और Node.js 16+ में ग्लोबली उपलब्ध है, लेकिन केवल Latin-1 (कोड पॉइंट 0–255) स्वीकार करती है — Unicode इनपुट DOMException फेंकता है
- ✓Buffer.from(text, "utf8").toString("base64") Node.js का समकक्ष है जो बिना किसी अतिरिक्त चरण के Unicode को नेटिव रूप से संभालता है
- ✓URL-safe Base64 + को → - और / को → _ से बदलता है, और = पैडिंग हटा देता है — एक-लाइनर के लिए Node.js 18+ में Buffer.from().toString("base64url") उपयोग करें
- ✓बाइनरी डेटा (ArrayBuffer, Uint8Array, फ़ाइलें) के लिए, Node.js में Buffer या ब्राउज़र में arrayBuffer() + Uint8Array दृष्टिकोण उपयोग करें — response.text() कभी नहीं
- ✓Uint8Array.prototype.toBase64() (TC39 Stage 3) पहले से ही Node.js 22+ और Chrome 130+ में उपलब्ध है और दोनों वातावरणों को एकीकृत करेगा
Base64 एनकोडिंग क्या है?
Base64 मनमाने बाइनरी डेटा को 64 प्रिंट करने योग्य ASCII वर्णों से बनी स्ट्रिंग में परिवर्तित करता है: A–Z, a–z, 0–9, +, और /। इनपुट के प्रत्येक 3 बाइट ठीक 4 Base64 वर्णों से मैप होते हैं; यदि इनपुट की लंबाई 3 का गुणज नहीं है, तो एक या दो पैडिंग वर्ण = जोड़े जाते हैं। एनकोडेड आउटपुट हमेशा मूल से लगभग 33% बड़ा होता है।
Base64 एन्क्रिप्शन नहीं है — यह कोई गोपनीयता प्रदान नहीं करता। एनकोडेड स्ट्रिंग वाला कोई भी व्यक्ति एक फ़ंक्शन कॉल में इसे डीकोड कर सकता है। इसका उद्देश्य ट्रांसपोर्ट सुरक्षा है: कई प्रोटोकॉल और स्टोरेज फॉर्मेट 7-बिट ASCII टेक्स्ट के लिए डिज़ाइन किए गए थे और मनमाने बाइनरी बाइट्स को संभाल नहीं सकते। Base64 उस अंतर को पाटता है। JavaScript के सामान्य उपयोग के मामलों में शामिल हैं: इनलाइनिंग एसेट के लिए data URI, HTTP Basic Auth हेडर, JWT टोकन सेगमेंट, ईमेल MIME अटैचमेंट, और JSON API में बाइनरी ब्लॉब स्टोर करना।
deploy-bot:sk-prod-a7f2c91e4b3d8
ZGVwbG95LWJvdDpzay1wcm9kLWE3ZjJjOTFlNGIzZDg=
btoa() — ब्राउज़र-नेटिव एनकोडिंग फ़ंक्शन
btoa() (binary-to-ASCII) IE10 से ब्राउज़रों में उपलब्ध है और WinterCG संगतता पहल के हिस्से के रूप में Node.js 16.0 में ग्लोबल बन गई। यह Deno, Bun, और Cloudflare Workers में भी नेटिव रूप से काम करती है। किसी इम्पोर्ट की आवश्यकता नहीं।
यह फ़ंक्शन एकल स्ट्रिंग तर्क लेता है और इसका Base64-एनकोडेड रूप लौटाता है। सममित समकक्ष atob() (ASCII-to-binary) इसे वापस डीकोड करती है। दोनों सिंक्रोनस हैं और इनपुट साइज के सापेक्ष निरंतर मेमोरी में चलते हैं।
न्यूनतम कार्यशील उदाहरण
// Encoding an API credential pair for an HTTP Basic Auth header
const serviceId = 'deploy-bot'
const apiKey = 'sk-prod-a7f2c91e4b3d8'
const credential = btoa(`${serviceId}:${apiKey}`)
// → 'ZGVwbG95LWJvdDpzay1wcm9kLWE3ZjJjOTFlNGIzZDg='
const headers = new Headers({
Authorization: `Basic ${credential}`,
'Content-Type': 'application/json',
})
console.log(headers.get('Authorization'))
// Basic ZGVwbG95LWJvdDpzay1wcm9kLWE3ZjJjOTFlNGIzZDg=atob() से डीकोडिंग
// Round-trip: encode, transmit, decode const payload = 'service:payments region:eu-west-1 env:production' const encoded = btoa(payload) const decoded = atob(encoded) console.log(encoded) // c2VydmljZTpwYXltZW50cyByZWdpb246ZXUtd2VzdC0xIGVudjpwcm9kdWN0aW9u console.log(decoded === payload) // true
btoa() और atob() WinterCG Minimum Common API का हिस्सा हैं — वही स्पेक जो नॉन-ब्राउज़र रनटाइम में Fetch, URL, और crypto को नियंत्रित करती है। ये Node.js 16+, Bun, Deno, और Cloudflare Workers में समान रूप से व्यवहार करती हैं।Unicode और Non-ASCII वर्णों को संभालना
btoa() का सबसे आम जाल इसकी सख्त Latin-1 सीमा है। U+00FF से ऊपर के कोड पॉइंट वाला कोई भी वर्ण तुरंत एक अपवाद का कारण बनता है:
btoa('Müller & Søren') // ❌ Uncaught DOMException: String contains an invalid character
btoa('résumé') // ❌ 'é' is U+00E9 = 233 — within Latin-1, this one actually works
btoa('田中太郎') // ❌ Throws — all CJK characters are above U+00FFसही दृष्टिकोण पहले स्ट्रिंग को UTF-8 बाइट्स में एनकोड करना है, फिर उन बाइट्स को Base64-एनकोड करना है। JavaScript इस उद्देश्य के लिए TextEncoder प्रदान करता है:
TextEncoder दृष्टिकोण — किसी भी Unicode इनपुट के लिए सुरक्षित
// Utility functions for Unicode-safe Base64
function toBase64(text: string): string {
const bytes = new TextEncoder().encode(text)
const chars = Array.from(bytes, byte => String.fromCharCode(byte))
return btoa(chars.join(''))
}
function fromBase64(encoded: string): string {
const binary = atob(encoded)
const bytes = Uint8Array.from(binary, ch => ch.charCodeAt(0))
return new TextDecoder().decode(bytes)
}
// Works with any language or script
const orderNote = 'पुष्टि: राहुल शर्मा — मुंबई गोदाम, मात्रा: 250'
const encoded = toBase64(orderNote)
const decoded = fromBase64(encoded)
console.log(encoded)
// 4KaA4Ka+4Ka/4KaF4Ka/OiDgprachingprachracingprachingprachingpraching...
console.log(decoded === orderNote) // trueBuffer.from(text, 'utf8').toString('base64') उपयोग करें। यह Unicode को नेटिव रूप से संभालता है और बड़ी स्ट्रिंग के लिए तेज़ है।Node.js में Buffer.from() — उदाहरणों के साथ पूर्ण गाइड
Node.js में, Buffer एनकोडिंग रूपांतरण सहित सभी बाइनरी डेटा ऑपरेशन के लिए idiomatic API है। यह TextEncoder से वर्षों पहले से है और सर्वर-साइड कोड के लिए पसंदीदा विकल्प बना हुआ है। btoa() की तुलना में मुख्य फायदे: नेटिव UTF-8 सपोर्ट, बाइनरी डेटा हैंडलिंग, और 'base64url' एनकोडिंग शॉर्टकट जो Node.js 18 से उपलब्ध है।
मूल टेक्स्ट एनकोडिंग और डीकोडिंग
// Encoding a server configuration object for storage in an env variable
const dbConfig = JSON.stringify({
host: 'db-primary.internal',
port: 5432,
database: 'analytics_prod',
maxConnections: 100,
ssl: { rejectUnauthorized: true },
})
const encoded = Buffer.from(dbConfig, 'utf8').toString('base64')
console.log(encoded)
// eyJob3N0IjoiZGItcHJpbWFyeS5pbnRlcm5hbCIsInBvcnQiOjU0MzIsImRhdGFiYXNlIjoiYW5h...
// Decoding back
const decoded = Buffer.from(encoded, 'base64').toString('utf8')
const config = JSON.parse(decoded)
console.log(config.host) // db-primary.internal
console.log(config.maxConnections) // 100डिस्क से बाइनरी फ़ाइलें एनकोड करना
import { readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
// Read a TLS certificate and encode it for embedding in a config file
const certPem = readFileSync(join(process.cwd(), 'ssl', 'server.crt'))
const certBase64 = certPem.toString('base64')
// Store as a single-line string — suitable for env vars or JSON configs
writeFileSync('./dist/cert.b64', certBase64, 'utf8')
console.log(`Certificate encoded: ${certBase64.length} characters`)
// Certificate encoded: 2856 characters
// Restore the binary cert from the encoded value
const restored = Buffer.from(certBase64, 'base64')
console.log(restored.equals(certPem)) // trueएरर हैंडलिंग के साथ async फ़ाइल एनकोडिंग
import { readFile } from 'node:fs/promises'
async function encodeFileToBase64(filePath: string): Promise<string> {
try {
const buffer = await readFile(filePath)
return buffer.toString('base64')
} catch (err) {
const code = (err as NodeJS.ErrnoException).code
if (code === 'ENOENT') throw new Error(`File not found: ${filePath}`)
if (code === 'EACCES') throw new Error(`Permission denied: ${filePath}`)
throw err
}
}
// Encode a PDF for an email attachment payload
const reportBase64 = await encodeFileToBase64('./reports/q1-financials.pdf')
const emailPayload = {
to: 'finance-team@company.internal',
subject: 'Q1 Financial Report',
attachments: [{
filename: 'q1-financials.pdf',
content: reportBase64,
encoding: 'base64',
contentType: 'application/pdf',
}],
}
console.log(`Attachment: ${reportBase64.length} chars`)JavaScript Base64 फ़ंक्शन — पैरामीटर संदर्भ
Python के base64 मॉड्यूल के विपरीत, JavaScript में कोई एकल एकीकृत Base64 फ़ंक्शन नहीं है। API लक्ष्य वातावरण पर निर्भर करता है। सभी नेटिव दृष्टिकोणों का पूर्ण संदर्भ यहाँ है:
| फ़ंक्शन | इनपुट प्रकार | Unicode | URL-safe | उपलब्ध में |
|---|---|---|---|---|
| btoa(string) | string (Latin-1) | ❌ U+00FF से ऊपर फेंकता है | ❌ मैनुअल रिप्लेस | Browser, Node 16+, Bun, Deno |
| atob(string) | Base64 string | ❌ बाइनरी स्ट्रिंग लौटाता है | ❌ मैनुअल रिप्लेस | Browser, Node 16+, Bun, Deno |
| Buffer.from(src, enc) .toString(enc) | string | Buffer | Uint8Array | ✅ utf8 एनकोडिंग | ✅ Node 18+ में base64url | Node.js, Bun |
| TextEncoder().encode(str) + btoa() | string (कोई भी Unicode) | ✅ UTF-8 बाइट्स के माध्यम से | ❌ मैनुअल रिप्लेस | Browser, Node 16+, Deno |
| Uint8Array.toBase64() (TC39) | Uint8Array | ✅ बाइनरी | ✅ omitPadding + alphabet | Chrome 130+, Node 22+ |
Buffer.from(src, enc).toString(enc) सिग्नेचर Base64 से संबंधित कई एनकोडिंग मान स्वीकार करता है:
URL-safe Base64 — JWT, URL, और फ़ाइल नामों के लिए एनकोडिंग
मानक Base64 + और / का उपयोग करता है, जो URL में आरक्षित हैं — + को query string में स्पेस के रूप में डीकोड किया जाता है, और / एक पाथ सेपरेटर है। JWT, URL पैरामीटर, फ़ाइल नाम, और कुकी वैल्यू सभी को URL-safe वेरिएंट की आवश्यकता है: + → -, / → _, trailing = हटाया गया।
ब्राउज़र — मैनुअल कैरेक्टर रिप्लेसमेंट
function toBase64Url(text: string): string {
// For ASCII-safe input (e.g., JSON with only ASCII chars)
return btoa(text)
.replace(/+/g, '-')
.replace(///g, '_')
.replace(/=/g, '')
}
function fromBase64Url(encoded: string): string {
// Restore standard Base64 characters and padding before decoding
const base64 = encoded.replace(/-/g, '+').replace(/_/g, '/')
const padded = base64 + '==='.slice(0, (4 - base64.length % 4) % 4)
return atob(padded)
}
// JWT header — must be URL-safe Base64
const header = JSON.stringify({ alg: 'HS256', typ: 'JWT' })
const encoded = toBase64Url(header)
console.log(encoded) // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
const decoded = fromBase64Url(encoded)
console.log(decoded) // {"alg":"HS256","typ":"JWT"}Node.js 18+ — नेटिव 'base64url' एनकोडिंग
// Node.js 18 added 'base64url' as a first-class Buffer encoding
const sessionPayload = JSON.stringify({
userId: 'usr_9f2a1c3e8b4d',
role: 'editor',
workspaceId:'ws_3a7f91c2',
exp: Math.floor(Date.now() / 1000) + 3600,
})
const encoded = Buffer.from(sessionPayload, 'utf8').toString('base64url')
// No + or / or = characters in the output
// eyJ1c2VySWQiOiJ1c3JfOWYyYTFjM2U4YjRkIiwicm9sZSI6ImVkaXRvciIsIndvcmtzcGFjZUlkIjoid3NfM2E3ZjkxYzIiLCJleHAiOjE3MTcyMDM2MDB9
const decoded = Buffer.from(encoded, 'base64url').toString('utf8')
console.log(JSON.parse(decoded).role) // editorJavaScript में फ़ाइलें और API रेस्पॉन्स एनकोड करना
प्रोडक्शन कोड में, Base64 एनकोडिंग अक्सर ट्रांसमिट की जा रही फ़ाइलों और बाइनरी सामग्री देने वाले बाहरी API के रेस्पॉन्स पर लागू होती है। पैटर्न ब्राउज़र और Node.js के बीच भिन्न होते हैं, और बाइनरी डेटा को विशेष देखभाल की आवश्यकता है।
ब्राउज़र — input एलिमेंट से फ़ाइल एनकोड करें
// Modern approach: File.arrayBuffer() (Chrome 76+, Firefox 69+, Safari 14+)
async function encodeFile(file: File): Promise<string> {
const buffer = await file.arrayBuffer()
const bytes = new Uint8Array(buffer)
const chars = Array.from(bytes, b => String.fromCharCode(b))
return btoa(chars.join(''))
}
const uploadInput = document.getElementById('avatar') as HTMLInputElement
uploadInput.addEventListener('change', async (e) => {
const file = (e.target as HTMLInputElement).files?.[0]
if (!file) return
try {
const encoded = await encodeFile(file)
const dataUri = `data:${file.type};base64,${encoded}`
// Preview the image inline
const img = document.getElementById('preview') as HTMLImageElement
img.src = dataUri
img.hidden = false
console.log(`Encoded ${file.name} (${file.size} bytes) → ${encoded.length} Base64 chars`)
} catch (err) {
console.error('Encoding failed:', err)
}
})API से Base64-एनकोडेड बाइनरी फेच करना
// GitHub Contents API returns file content as Base64 with embedded newlines
async function fetchRepoFile(
owner: string,
repo: string,
path: string,
token: string,
): Promise<string> {
const res = await fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/${path}`,
{
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/vnd.github.v3+json',
},
}
)
if (!res.ok) throw new Error(`GitHub API ${res.status}: ${res.statusText}`)
const data = await res.json() as { content: string; encoding: string; size: number }
if (data.encoding !== 'base64') {
throw new Error(`Unexpected encoding from GitHub: ${data.encoding}`)
}
// GitHub wraps output at 60 chars — strip newlines before decoding
const clean = data.content.replace(/\n/g, '')
return atob(clean)
}
const openApiSpec = await fetchRepoFile(
'acme-corp', 'platform-api', 'openapi.json', process.env.GITHUB_TOKEN!
)
const spec = JSON.parse(openApiSpec)
console.log(`API version: ${spec.info.version}`)जब आपको स्क्रिप्ट सेट किए बिना API डीबगिंग के दौरान एनकोडेड रेस्पॉन्स जांचना हो, तो Base64 वैल्यू सीधे Base64 Encoder में पेस्ट करें — यह तुरंत आउटपुट के साथ डीकोड भी करता है। GitHub API रेस्पॉन्स, JWT पेलोड, और webhook सिग्नेचर जांचने के लिए उपयोगी।
Node.js और Shell में Command-Line Base64 एनकोडिंग
CI/CD स्क्रिप्ट, Makefile टार्गेट, या एक बार की डीबगिंग के लिए, आपको शायद ही पूरी स्क्रिप्ट की आवश्यकता होती है। सिस्टम टूल और Node.js one-liner दोनों क्रॉस-प्लेटफ़ॉर्म पर अधिकांश मामलों को कवर करते हैं।
# ── macOS / Linux system base64 ───────────────────────────────────────
# Standard encoding
echo -n "deploy-bot:sk-prod-a7f2c91e4b3d8" | base64
# ZGVwbG95LWJvdDpzay1wcm9kLWE3ZjJjOTFlNGIzZDg=
# URL-safe variant (replace chars and strip padding)
echo -n "deploy-bot:sk-prod-a7f2c91e4b3d8" | base64 | tr '+/' '-_' | tr -d '='
# Encode a file inline (macOS: -b 0 removes line wrapping; Linux: --wrap=0)
base64 -b 0 ./config/production.json
# or on Linux:
base64 --wrap=0 ./config/production.json
# Decode
echo "ZGVwbG95LWJvdDpzay1wcm9kLWE3ZjJjOTFlNGIzZDg=" | base64 --decode
# ── Node.js one-liner — works on Windows too ───────────────────────────
node -e "process.stdout.write(Buffer.from(process.argv[1]).toString('base64'))" "my:secret"
# bXk6c2VjcmV0
# URL-safe from Node.js 18+
node -e "process.stdout.write(Buffer.from(process.argv[1]).toString('base64url'))" "my:secret"
# bXk6c2VjcmV0 (same here since there are no special chars)
# Decode in Node.js
node -e "console.log(Buffer.from(process.argv[1], 'base64').toString())" "ZGVwbG95LWJvdA=="base64 डिफ़ॉल्ट रूप से 76 वर्णों पर आउटपुट रैप करता है। यह डाउनस्ट्रीम पार्सिंग को तोड़ता है। हमेशा -b 0 (macOS) या --wrap=0 (Linux) जोड़ें जब आपको एकल-पंक्ति परिणाम की आवश्यकता हो — उदाहरण के लिए, एनवायरनमेंट वेरिएबल या कॉन्फ़िग फ़ील्ड में लिखते समय।उच्च-प्रदर्शन विकल्प: js-base64
बिल्ट-इन API अधिकांश उपयोग के मामलों के लिए ठीक हैं। लाइब्रेरी का उपयोग करने का मुख्य कारण क्रॉस-एनवायरनमेंट स्थिरता है: यदि आप एक पैकेज शिप करते हैं जो ब्राउज़र और Node.js दोनों में चलता है, Buffer का उपयोग करने के लिए या तो एनवायरनमेंट डिटेक्शन या बंडलर कॉन्फ़िगरेशन की आवश्यकता है, जबकि btoa() को Unicode वर्कअराउंड की। js-base64 (npm पर 100M+ साप्ताहिक डाउनलोड) दोनों को पारदर्शी रूप से संभालता है।
npm install js-base64 # or pnpm add js-base64
import { toBase64, fromBase64, toBase64Url, fromBase64Url, isValid } from 'js-base64'
// Standard encoding — Unicode-safe, works in browser and Node.js
const telemetryEvent = JSON.stringify({
eventId: 'evt_7c3a9f1b2d',
type: 'checkout_completed',
currency: 'EUR',
amount: 14900,
userId: 'usr_4e2b8d6a5c',
timestamp: 1717200000,
})
const encoded = toBase64(telemetryEvent)
const urlEncoded = toBase64Url(telemetryEvent) // No +, /, or = characters
const decoded = fromBase64(encoded)
console.log(JSON.parse(decoded).type) // checkout_completed
// Binary data — pass a Uint8Array as second argument
const pngMagicBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
const binaryEncoded = toBase64(pngMagicBytes, true) // true = binary mode
// Validation before decoding
const suspicious = 'not!valid@base64#'
console.log(isValid(suspicious)) // falseहुड के नीचे, js-base64 उपलब्ध होने पर नेटिव Buffer का उपयोग करती है और ब्राउज़र में pure-JS इम्प्लीमेंटेशन पर फ़ॉलबैक करती है। यह बड़ी Unicode स्ट्रिंग के लिए TextEncoder+btoa दृष्टिकोण से 2–3× तेज़ है, और सममित API ( toBase64 / fromBase64) यह याद रखने का मानसिक बोझ समाप्त करती है कि btoa और atob किस दिशा में जाते हैं।
Node.js Streams के साथ बड़ी बाइनरी फ़ाइलें एनकोड करना
जब आपको ~50 MB से बड़ी फ़ाइलें एनकोड करनी हों, readFileSync() के साथ पूरी फ़ाइल को मेमोरी में लोड करना एक समस्या बन जाती है। Node.js स्ट्रीम आपको डेटा को चंक में प्रोसेस करने देती हैं — लेकिन Base64 एनकोडिंग में एक बाधा है: आपको चंक बाउंड्री पर गलत पैडिंग से बचने के लिए एनकोडर को 3 बाइट के गुणजों में फ़ीड करना होगा।
import { createReadStream, createWriteStream } from 'node:fs'
import { pipeline } from 'node:stream/promises'
// Stream a large binary file to a Base64-encoded output file
async function streamEncodeToBase64(
inputPath: string,
outputPath: string,
): Promise<void> {
const readStream = createReadStream(inputPath, { highWaterMark: 3 * 1024 * 256 }) // 768 KB chunks (multiple of 3)
const writeStream = createWriteStream(outputPath, { encoding: 'utf8' })
let buffer = Buffer.alloc(0)
await pipeline(
readStream,
async function* (source) {
for await (const chunk of source) {
buffer = Buffer.concat([buffer, chunk as Buffer])
// Encode in complete 3-byte groups to avoid mid-stream padding
const remainder = buffer.length % 3
const safe = buffer.subarray(0, buffer.length - remainder)
buffer = buffer.subarray(buffer.length - remainder)
if (safe.length > 0) yield safe.toString('base64')
}
// Flush remaining bytes (may add 1 or 2 '=' padding chars)
if (buffer.length > 0) yield buffer.toString('base64')
},
writeStream,
)
}
// Usage: encode a 200 MB video attachment
await streamEncodeToBase64(
'./uploads/product-demo.mp4',
'./dist/product-demo.b64',
)
console.log('Stream encoding complete')= पैडिंग से बचने के लिए चंक साइज 3 बाइट का गुणज होना चाहिए। उदाहरण 3 * 1024 * 256 = 786,432 बाइट (768 KB) का उपयोग करता है — अपने मेमोरी बजट के आधार पर highWaterMark समायोजित करें। 50 MB से कम फ़ाइलों के लिए, readFile() + Buffer.toString('base64') सरल और पर्याप्त तेज़ है।सामान्य गलतियाँ
मैंने Base64 एनकोडिंग के साथ कई JavaScript कोडबेस की समीक्षा की है, और ये चार गलतियाँ लगातार दिखाई देती हैं — अक्सर तब तक अनदेखी रहती हैं जब तक प्रोडक्शन में एनकोडिंग पाथ पर कोई non-ASCII वर्ण या बाइनरी फ़ाइल न पहुँचे।
गलती 1 — Unicode सीधे btoa() को पास करना
समस्या: btoa() केवल कोड पॉइंट 0–255 वाले वर्ण स्वीकार करती है। ñ, इमोजी, या CJK आइडियोग्राफ जैसे वर्ण तुरंत DOMException का कारण बनते हैं। समाधान: पहले TextEncoder से एनकोड करें, या Node.js में Buffer.from(text, 'utf8').toString('base64') उपयोग करें।
// ❌ DOMException: The string to be encoded contains // characters outside of the Latin1 range const username = 'प्रिया गुप्ता' const encoded = btoa(username) // throws
// ✅ Encode as UTF-8 bytes first
function safeEncode(text: string): string {
const bytes = new TextEncoder().encode(text)
const chars = Array.from(bytes, b => String.fromCharCode(b))
return btoa(chars.join(''))
}
const encoded = safeEncode('प्रिया गुप्ता')
// 4KaA4KauaKauaKauaKa+4KauaKa=गलती 2 — atob() से पहले पैडिंग रिस्टोर करना भूलना
समस्या: URL-safe Base64 = पैडिंग हटा देता है। स्ट्रिप की गई स्ट्रिंग को सीधे atob() को पास करने से स्ट्रिंग की लंबाई के आधार पर गलत आउटपुट या अपवाद होता है। समाधान: atob() कॉल करने से पहले + और / रिस्टोर करें और सही मात्रा में पैडिंग वापस जोड़ें।
// ❌ atob() may return wrong data or throw // on URL-safe Base64 without padding const jwtSegment = 'eyJ1c2VySWQiOiJ1c3JfOWYyYTFjM2UifQ' const decoded = atob(jwtSegment) // Unreliable
// ✅ Restore characters and padding first
function decodeBase64Url(input: string): string {
const b64 = input.replace(/-/g, '+').replace(/_/g, '/')
const pad = b64 + '==='.slice(0, (4 - b64.length % 4) % 4)
return atob(pad)
}
const decoded = decodeBase64Url('eyJ1c2VySWQiOiJ1c3JfOWYyYTFjM2UifQ')
// {"userId":"usr_9f2a1c3e"}गलती 3 — कच्चे बफर के बजाय एनकोडेड चंक जोड़ना
समस्या: btoa() या .toString('base64') का प्रत्येक कॉल अपना पैडिंग जोड़ता है। दो पैडेड Base64 स्ट्रिंग जोड़ने से अमान्य आउटपुट होता है क्योंकि पैडिंग केवल अंत में होनी चाहिए। समाधान: एनकोड करने से पहले कच्चे डेटा को जोड़ें।
// ❌ Both parts are padded independently —
// the combined string is not valid Base64
const part1 = Buffer.from('webhook-secret').toString('base64')
// d2ViaG9vay1zZWNyZXQ= ← has padding
const part2 = Buffer.from('-v2').toString('base64')
// LXYy ← correct in isolation
const combined = part1 + part2 // ❌ Invalid — padding in the middle// ✅ Concatenate raw Buffers before encoding
const combined = Buffer.concat([
Buffer.from('webhook-secret'),
Buffer.from('-v2'),
]).toString('base64')
// d2ViaG9vay1zZWNyZXQtdjI= — single valid Base64 stringगलती 4 — एनकोडिंग से पहले बाइनरी API डेटा पढ़ने के लिए response.text() उपयोग करना
समस्या: response.text() कच्चे बाइट्स को UTF-8 के रूप में इंटरप्रेट करता है और अपरिचित बाइट सीक्वेंस को रिप्लेसमेंट कैरेक्टर U+FFFD से बदल देता है। कोई भी बाइनरी सामग्री — इमेज, PDF, ऑडियो — btoa() तक पहुँचने से पहले चुपचाप खराब हो जाती है। समाधान: कच्चे बाइट्स प्राप्त करने के लिए response.arrayBuffer() उपयोग करें।
// ❌ response.text() corrupts binary data
const res = await fetch('/api/exports/invoice.pdf')
const text = await res.text() // ❌ PDF bytes mangled as UTF-8
const encoded = btoa(text) // ❌ Corrupted Base64// ✅ arrayBuffer() preserves raw bytes
const res = await fetch('/api/exports/invoice.pdf')
const buffer = await res.arrayBuffer()
const bytes = new Uint8Array(buffer)
const chars = Array.from(bytes, b => String.fromCharCode(b))
const encoded = btoa(chars.join('')) // ✅ Valid Base64JavaScript Base64 विधियाँ — त्वरित तुलना
| विधि | Unicode | बाइनरी डेटा | URL-safe | वातावरण | इंस्टॉल आवश्यक |
|---|---|---|---|---|---|
| btoa() / atob() | ❌ Latin-1 | ❌ वर्कअराउंड चाहिए | ❌ मैनुअल रिप्लेस | Browser, Node 16+, Bun, Deno | नहीं |
| TextEncoder + btoa() | ✅ UTF-8 | ✅ Uint8Array के माध्यम से | ❌ मैनुअल रिप्लेस | Browser, Node 16+, Deno | नहीं |
| Buffer.from().toString() | ✅ utf8 | ✅ नेटिव | ✅ base64url (Node 18+) | Node.js, Bun | नहीं |
| Uint8Array.toBase64() (TC39) | ✅ बाइनरी | ✅ नेटिव | ✅ alphabet विकल्प | Chrome 130+, Node 22+ | नहीं |
| js-base64 | ✅ हमेशा | ✅ Uint8Array | ✅ बिल्ट-इन | सार्वभौमिक | npm install |
btoa() केवल तभी चुनें जब इनपुट सिद्ध रूप से ASCII-only हो — hex डाइजेस्ट, न्यूमेरिक ID, या पूर्व-मान्य Latin-1 स्ट्रिंग। ब्राउज़र में उपयोगकर्ता-प्रदत्त टेक्स्ट के लिए, TextEncoder + btoa() उपयोग करें। सभी Node.js सर्वर-साइड कोड के लिए, Buffer सही डिफ़ॉल्ट है। उन लाइब्रेरी के लिए जिन्हें बंडलर कॉन्फ़िगरेशन के बिना दोनों वातावरणों में चलना है, js-base64 सभी एज केस हटा देती है।
अक्सर पूछे जाने वाले प्रश्न
संबंधित टूल
बिना कोई कोड लिखे एक-क्लिक एनकोड या डीकोड के लिए, अपनी स्ट्रिंग या बाइनरी को सीधे Base64 Encoder में पेस्ट करें — यह आपके ब्राउज़र में मानक और URL-safe दोनों मोड तुरंत संभालता है।
Alex is a front-end and Node.js developer with extensive experience building web applications and developer tooling. He is passionate about web standards, browser APIs, and the JavaScript ecosystem. In his spare time he contributes to open-source projects and writes about modern JavaScript patterns, performance optimisation, and everything related to the web platform.
Sophie is a full-stack developer focused on TypeScript across the entire stack — from React frontends to Express and Fastify backends. She has a particular interest in type-safe API design, runtime validation, and the patterns that make large JavaScript codebases stay manageable. She writes about TypeScript idioms, Node.js internals, and the ever-evolving JavaScript module ecosystem.