JavaScript में Base64 Decode — atob() & Buffer
मुफ़्त Base64 Decode Online को सीधे अपने ब्राउज़र में उपयोग करें — इंस्टॉलेशन की ज़रूरत नहीं।
Base64 Decode Online ऑनलाइन आज़माएं →जब मैं प्रोडक्शन ऑथ समस्या डीबग करता हूँ, तो मैं सबसे पहले Base64 डिकोडर का उपयोग करता हूँ — JWT पेलोड, वेबहुक सिग्नेचर, और एनकोडेड कॉन्फिग वैल्यू सभी Base64 स्ट्रिंग के अंदर छुपे होते हैं। JavaScript base64 डिकोड करने के लिए दो प्राथमिक बिल्ट-इन तरीके प्रदान करता है: atob() (browser + Node.js 16+) और Buffer.from(encoded, 'base64').toString() (Node.js) — और जब मूल डेटा में Unicode वर्ण होते हैं तो ये बहुत अलग व्यवहार करते हैं। बिना कोई कोड लिखे एक बार के डिकोड के लिए, ToolDeck का Base64 डिकोडर आपके ब्राउज़र में तुरंत इसे संभाल लेता है। यह गाइड दोनों वातावरणों को कवर करती है — Node.js 16+ और आधुनिक ब्राउज़र (Chrome 80+, Firefox 75+, Safari 14+) को लक्षित करते हुए — प्रोडक्शन-रेडी उदाहरणों के साथ: UTF-8 रिकवरी, URL-safe वेरिएंट, JWT डिकोडिंग, फ़ाइलें, API प्रतिक्रियाएं, Node.js streams, और चार गलतियाँ जो लगातार वास्तविक कोडबेस में गड़बड़ आउटपुट उत्पन्न करती हैं।
- ✓atob(encoded) ब्राउज़र में नेटिव रूप से उपलब्ध है और Node.js 16+ में ग्लोबली, लेकिन यह एक binary string लौटाता है — ASCII से ऊपर किसी भी कंटेंट से UTF-8 टेक्स्ट पुनः प्राप्त करने के लिए TextDecoder का उपयोग करें।
- ✓Buffer.from(encoded, "base64").toString("utf8") Node.js का मुहावरेदार तरीका है और बिना किसी अतिरिक्त चरण के UTF-8 को स्वचालित रूप से संभालता है।
- ✓URL-safe Base64 (JWT में उपयोग) + को - से, / को _ से बदलता है, और = पैडिंग हटाता है। atob() कॉल करने से पहले इन्हें पुनर्स्थापित करें, या Node.js 18+ में Buffer.from(encoded, "base64url").toString() उपयोग करें।
- ✓डिकोड करने से पहले व्हाइटस्पेस और न्यूलाइन हटाएं — GitHub Contents API और कई MIME एनकोडर Base64 आउटपुट को 60–76 वर्ण प्रति पंक्ति पर रैप करते हैं।
- ✓Uint8Array.prototype.fromBase64() (TC39 Stage 3) Node.js 22+ और Chrome 130+ में पहले से उपलब्ध है और अंततः दोनों वातावरणों को एकीकृत करेगा।
Base64 डिकोडिंग क्या है?
Base64 डिकोडिंग एनकोडिंग का उल्टा है — यह 64-वर्ण ASCII प्रतिनिधित्व को वापस मूल बाइनरी डेटा या टेक्स्ट में परिवर्तित करता है। हर 4 Base64 वर्ण ठीक 3 बाइट्स में मैप होते हैं। एनकोडेड स्ट्रिंग के अंत में = पैडिंग वर्ण डिकोडर को बताते हैं कि अंतिम 3-बाइट समूह पूरा करने के लिए कितने अतिरिक्त बाइट जोड़े गए थे।
Base64 एन्क्रिप्शन नहीं है — ऑपरेशन एनकोडेड स्ट्रिंग वाले किसी के द्वारा भी पूरी तरह से उलटा किया जा सकता है। इसका उद्देश्य ट्रांसपोर्ट सुरक्षा है: 7-बिट ASCII टेक्स्ट के लिए डिज़ाइन किए गए प्रोटोकॉल और स्टोरेज फॉर्मेट मनमाने बाइनरी बाइट्स को संभाल नहीं सकते, और Base64 उस अंतर को पाटता है। सामान्य JavaScript डिकोडिंग परिदृश्यों में JWT पेलोड की जांच करना, एनवायरनमेंट वेरिएबल से Base64-एनकोडेड JSON कॉन्फिग अनपैक करना, REST API से बाइनरी फ़ाइल कंटेंट निकालना, और ब्राउज़र में डेटा URI डिकोड करना शामिल हैं।
ZGVwbG95LWJvdDpzay1wcm9kLWE3ZjJjOTFlNGIzZDg=
deploy-bot:sk-prod-a7f2c91e4b3d8
atob() — ब्राउज़र-नेटिव डिकोडिंग फ़ंक्शन
atob() (ASCII-to-binary) IE10 से ब्राउज़र में उपलब्ध है और WinterCG कम्पेटिबिलिटी इनिशिएटिव के हिस्से के रूप में Node.js 16.0 में ग्लोबल बन गया। यह Deno, Bun, और Cloudflare Workers में भी नेटिव रूप से काम करता है — कोई import आवश्यक नहीं।
फ़ंक्शन एक binary string लौटाता है: एक JavaScript स्ट्रिंग जहाँ प्रत्येक वर्ण का code point एक raw बाइट वैल्यू (0–255) के बराबर होता है। यह महत्वपूर्ण है: यदि मूल डेटा UTF-8 टेक्स्ट था जिसमें U+007F से ऊपर के वर्ण थे (एक्सेंटेड अक्षर, Cyrillic, CJK, emoji), तो लौटाई गई स्ट्रिंग raw बाइट सीक्वेंस है, पठनीय टेक्स्ट नहीं। इसे पुनः प्राप्त करने के लिए TextDecoder का उपयोग करें (अगले सेक्शन में कवर किया गया)।
न्यूनतम कार्यशील उदाहरण
// Decoding an HTTP Basic Auth credential pair received in a request header
// Authorization: Basic ZGVwbG95LWJvdDpzay1wcm9kLWE3ZjJjOTFlNGIzZDg=
function parseBasicAuth(header: string): { serviceId: string; apiKey: string } {
const base64Part = header.replace(/^Basics+/i, '')
const decoded = atob(base64Part)
const [serviceId, apiKey] = decoded.split(':')
return { serviceId, apiKey }
}
const auth = parseBasicAuth('Basic ZGVwbG95LWJvdDpzay1wcm9kLWE3ZjJjOTFlNGIzZDg=')
console.log(auth.serviceId) // deploy-bot
console.log(auth.apiKey) // sk-prod-a7f2c91e4b3d8Round-trip सत्यापन
// Verify lossless recovery for ASCII-only content const original = 'service:payments region:eu-west-1 env:production' const encoded = btoa(original) const decoded = atob(encoded) console.log(encoded) // c2VydmljZTpwYXltZW50cyByZWdpb246ZXUtd2VzdC0xIGVudjpwcm9kdWN0aW9u console.log(decoded === original) // true
atob() और btoa() WinterCG Minimum Common API का हिस्सा हैं — वही spec जो non-browser रनटाइम में Fetch, URL, और crypto को नियंत्रित करता है। ये Node.js 16+, Bun, Deno, और Cloudflare Workers में समान रूप से व्यवहार करते हैं।डिकोडिंग के बाद UTF-8 टेक्स्ट पुनः प्राप्त करना
atob() की सबसे आम समस्या इसके रिटर्न टाइप को गलत समझना है। जब मूल टेक्स्ट को Base64 से पहले UTF-8 के रूप में एनकोड किया गया था, atob() एक Latin-1 binary string लौटाता है, पठनीय टेक्स्ट नहीं:
// 'Алексей Иванов' was UTF-8 encoded then Base64 encoded before transmission const encoded = '0JDQu9C10LrRgdC10Lkg0JjQstCw0L3QvtCy' // ❌ atob() returns the raw UTF-8 bytes as a Latin-1 string — garbled output console.log(atob(encoded)) // "Алексей Р˜РІР°РЅРѕРІ" ← byte values misread as Latin-1
सही तरीका उन raw बाइट्स को UTF-8 के रूप में व्याख्या करने के लिए TextDecoder का उपयोग करता है:
TextDecoder दृष्टिकोण — किसी भी Unicode आउटपुट के लिए सुरक्षित
// Unicode-safe Base64 decode utilities
function fromBase64(encoded: string): string {
const binary = atob(encoded)
const bytes = Uint8Array.from(binary, ch => ch.charCodeAt(0))
return new TextDecoder().decode(bytes)
}
function toBase64(text: string): string {
const bytes = new TextEncoder().encode(text)
const chars = Array.from(bytes, byte => String.fromCharCode(byte))
return btoa(chars.join(''))
}
// Works with any language or script
const orderNote = 'Confirmed: 田中太郎 — São Paulo warehouse, qty: 250'
const encoded = toBase64(orderNote)
const decoded = fromBase64(encoded)
console.log(decoded === orderNote) // true
console.log(decoded)
// Confirmed: 田中太郎 — São Paulo warehouse, qty: 250Buffer.from(encoded, 'base64').toString('utf8') का उपयोग करें। यह डिकोड किए गए बाइट्स को स्वचालित रूप से UTF-8 के रूप में व्याख्या करता है और बड़े इनपुट के लिए तेज़ है।Node.js में Buffer.from() — संपूर्ण डिकोडिंग गाइड
Node.js में, Buffer Base64 डिकोडिंग सहित सभी बाइनरी ऑपरेशन के लिए मुहावरेदार API है। यह UTF-8 को नेटिव रूप से संभालता है, एक उचित Buffer (बाइनरी-सेफ) लौटाता है, और Node.js 18 से URL-safe वेरिएंट के लिए 'base64url' एनकोडिंग शॉर्टकट का समर्थन करता है।
एनवायरनमेंट वेरिएबल कॉन्फिग डिकोड करना
// Server config stored as Base64 in an env variable (avoids JSON escaping in shell)
// DB_CONFIG=eyJob3N0IjoiZGItcHJpbWFyeS5pbnRlcm5hbCIsInBvcnQiOjU0MzIsImRhdGFiYXNlIjoiYW5hbHl0aWNzX3Byb2QiLCJtYXhDb25uZWN0aW9ucyI6MTAwfQ==
const raw = Buffer.from(process.env.DB_CONFIG!, 'base64').toString('utf8')
const dbConfig = JSON.parse(raw)
console.log(dbConfig.host) // db-primary.internal
console.log(dbConfig.port) // 5432
console.log(dbConfig.maxConnections) // 100.b64 फ़ाइल से बाइनरी फ़ाइल पुनर्स्थापित करना
import { readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
// Read the Base64-encoded certificate and restore the original binary
const encoded = readFileSync(join(process.cwd(), 'dist', 'cert.b64'), 'utf8').trim()
const certBuf = Buffer.from(encoded, 'base64')
writeFileSync('./ssl/server.crt', certBuf)
console.log(`Restored ${certBuf.length} bytes`)
// Restored 2142 byteserror handling के साथ async डिकोडिंग
import { readFile, writeFile } from 'node:fs/promises'
async function decodeBase64File(
encodedPath: string,
outputPath: string,
): Promise<number> {
try {
const encoded = await readFile(encodedPath, 'utf8')
const binary = Buffer.from(encoded.trim(), 'base64')
await writeFile(outputPath, binary)
return binary.length
} catch (err) {
const code = (err as NodeJS.ErrnoException).code
if (code === 'ENOENT') throw new Error(`File not found: ${encodedPath}`)
if (code === 'EACCES') throw new Error(`Permission denied: ${encodedPath}`)
throw err
}
}
// Restore a PDF stored as Base64
const bytes = await decodeBase64File('./uploads/invoice.b64', './out/invoice.pdf')
console.log(`Decoded ${bytes} bytes — PDF restored`)Base64 डिकोडिंग फ़ंक्शन — पैरामीटर संदर्भ
दो प्राथमिक नेटिव डिकोडिंग API के पैरामीटर के लिए त्वरित संदर्भ, कोड लिखते या समीक्षा करते समय लुकअप के रूप में उपयोग के लिए फॉर्मेट किया गया।
atob(encodedData)
| पैरामीटर | टाइप | आवश्यक | विवरण |
|---|---|---|---|
| encodedData | string | हाँ | +, /, = वर्णों का उपयोग करने वाली मानक Base64 स्ट्रिंग। URL-safe वेरिएंट (-, _) InvalidCharacterError थ्रो करते हैं। व्हाइटस्पेस अनुमत नहीं है। |
Buffer.from(input, inputEncoding) / .toString(outputEncoding)
| पैरामीटर | टाइप | डिफ़ॉल्ट | विवरण |
|---|---|---|---|
| input | string | Buffer | TypedArray | ArrayBuffer | आवश्यक | डिकोड करने के लिए Base64-एनकोडेड स्ट्रिंग, या एनकोडेड बाइट्स वाला buffer। |
| inputEncoding | BufferEncoding | "utf8" | मानक Base64 के लिए "base64" (RFC 4648 §4), या URL-safe Base64 के लिए "base64url" (RFC 4648 §5, Node.js 18+) पर सेट करें। |
| outputEncoding | string | "utf8" | .toString() आउटपुट के लिए एनकोडिंग। पठनीय टेक्स्ट के लिए "utf8" उपयोग करें, atob() आउटपुट के साथ संगत Latin-1 binary string के लिए "binary"। |
| start | integer | 0 | पढ़ना शुरू करने के लिए डिकोड किए गए Buffer के भीतर बाइट ऑफसेट। .toString() को दूसरे तर्क के रूप में पास किया जाता है। |
| end | integer | buf.length | पढ़ना बंद करने के लिए बाइट ऑफसेट (एक्सक्लूसिव)। .toString() को तीसरे तर्क के रूप में पास किया जाता है। |
URL-safe Base64 — JWT और URL पैरामीटर डिकोड करना
JWT सभी तीन सेगमेंट के लिए URL-safe Base64 (RFC 4648 §5) का उपयोग करते हैं। URL-safe Base64 + को - से और / को _ से बदलता है, और पीछे के = पैडिंग हटाता है। बिना पुनर्स्थापना के इसे सीधे atob() में पास करने से गलत आउटपुट मिलता है या error थ्रो होती है।
Browser — डिकोड करने से पहले वर्ण और पैडिंग पुनर्स्थापित करें
function decodeBase64Url(input: string): string {
const base64 = input.replace(/-/g, '+').replace(/_/g, '/')
const padded = base64 + '==='.slice(0, (4 - base64.length % 4) % 4)
const binary = atob(padded)
const bytes = Uint8Array.from(binary, ch => ch.charCodeAt(0))
return new TextDecoder().decode(bytes)
}
// Inspect a JWT payload segment (the middle part between the two dots)
const jwtToken = 'eyJ1c2VySWQiOiJ1c3JfOWYyYTFjM2U4YjRkIiwicm9sZSI6ImVkaXRvciIsIndvcmtzcGFjZUlkIjoid3NfM2E3ZjkxYzIiLCJleHAiOjE3MTcyMDM2MDB9'
const payload = decodeBase64Url(jwtToken)
const claims = JSON.parse(payload)
console.log(claims.userId) // usr_9f2a1c3e8b4d
console.log(claims.role) // editor
console.log(claims.workspaceId) // ws_3a7f91c2Node.js 18+ — नेटिव 'base64url' एनकोडिंग
// Node.js 18 added 'base64url' as a first-class Buffer encoding — no manual replace needed
function decodeJwtSegment(segment: string): Record<string, unknown> {
const json = Buffer.from(segment, 'base64url').toString('utf8')
return JSON.parse(json)
}
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c3JfOWYyYTFjM2U4YjRkIiwicm9sZSI6ImVkaXRvciIsIndvcmtzcGFjZUlkIjoid3NfM2E3ZjkxYzIiLCJleHAiOjE3MTcyMDM2MDB9.SIGNATURE'
const [headerB64, payloadB64] = token.split('.')
const header = decodeJwtSegment(headerB64)
const payload = decodeJwtSegment(payloadB64)
console.log(header.alg) // HS256
console.log(payload.role) // editor
console.log(payload.workspaceId) // ws_3a7f91c2फ़ाइलों और API प्रतिक्रियाओं से Base64 डिकोड करना
प्रोडक्शन कोड में, Base64 डिकोडिंग सबसे अधिक तब होती है जब बाहरी API का उपयोग किया जाता है जो एनकोडेड रूप में कंटेंट डिलीवर करते हैं। दोनों परिदृश्यों में व्हाइटस्पेस और बाइनरी बनाम टेक्स्ट आउटपुट के आसपास महत्वपूर्ण gotchas हैं। यदि आप डीबगिंग के दौरान एनकोडेड प्रतिक्रिया की जांच करना चाहते हैं, तो इसे सीधे Base64 डिकोडर में पेस्ट करें — यह तुरंत मानक और URL-safe दोनों मोड संभालता है।
GitHub Contents API से कंटेंट डिकोड करना
// GitHub Contents API returns file content as Base64, wrapped at 60 chars per line
async function fetchDecodedFile(
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 }
if (data.encoding !== 'base64') throw new Error(`Unexpected encoding: ${data.encoding}`)
// ⚠️ GitHub wraps at 60 chars — strip newlines before decoding
const clean = data.content.replace(/\n/g, '')
return Buffer.from(clean, 'base64').toString('utf8')
}
const openApiSpec = await fetchDecodedFile('acme-corp', 'platform-api', 'openapi.json', process.env.GITHUB_TOKEN!)
const spec = JSON.parse(openApiSpec)
console.log(`API version: ${spec.info.version}`)API से Base64-एनकोडेड बाइनरी डिकोड करना (browser)
// Some APIs return binary content (images, PDFs) as Base64 JSON fields
async function downloadDecodedFile(endpoint: string, authToken: string): Promise<void> {
const res = await fetch(endpoint, { headers: { Authorization: `Bearer ${authToken}` } })
if (!res.ok) throw new Error(`Download failed: ${res.status}`)
const { filename, content, mimeType } = await res.json() as {
filename: string; content: string; mimeType: string
}
// Decode Base64 → binary bytes → Blob
const binary = atob(content)
const bytes = Uint8Array.from(binary, ch => ch.charCodeAt(0))
const blob = new Blob([bytes], { type: mimeType })
// Trigger browser download
const url = URL.createObjectURL(blob)
const a = Object.assign(document.createElement('a'), { href: url, download: filename })
a.click()
URL.revokeObjectURL(url)
}
await downloadDecodedFile('/api/reports/latest', sessionStorage.getItem('auth_token')!)Node.js और Shell में Command-Line Base64 डिकोडिंग
CI/CD स्क्रिप्ट, डीबगिंग सेशन, या एक बार के डिकोडिंग कार्यों के लिए, shell टूल और Node.js one-liner पूरी स्क्रिप्ट से तेज़ हैं। ध्यान दें कि macOS और Linux के बीच flag का नाम अलग होता है।
# ── macOS / Linux system base64 ───────────────────────────────────────
# Standard decoding (macOS uses -D, Linux uses -d)
echo "ZGVwbG95LWJvdDpzay1wcm9kLWE3ZjJjOTFlNGIzZDg=" | base64 -d # Linux
echo "ZGVwbG95LWJvdDpzay1wcm9kLWE3ZjJjOTFlNGIzZDg=" | base64 -D # macOS
# Decode a .b64 file to its original binary
base64 -d ./dist/cert.b64 > ./ssl/server.crt # Linux
base64 -D -i ./dist/cert.b64 -o ./ssl/server.crt # macOS
# URL-safe Base64 — restore + and / before decoding
echo "eyJ1c2VySWQiOiJ1c3JfOWYyYTFjM2UifQ" | tr '-_' '+/' | base64 -d
# ── Node.js one-liner — works on Windows too ───────────────────────────
node -e "process.stdout.write(Buffer.from(process.argv[1], 'base64').toString())" "ZGVwbG95LWJvdA=="
# deploy-bot
# URL-safe (Node.js 18+)
node -e "process.stdout.write(Buffer.from(process.argv[1], 'base64url').toString())" "eyJhbGciOiJIUzI1NiJ9"
# {"alg":"HS256"}base64 डिकोड करने के लिए -D (बड़ा D) उपयोग करता है, जबकि Linux -d (छोटा) उपयोग करता है। यह CI स्क्रिप्ट को चुपचाप तोड़ता है — जब टार्गेट प्लेटफॉर्म Linux की गारंटी न हो तो Node.js one-liner उपयोग करें।उच्च-प्रदर्शन विकल्प: js-base64
library तक पहुंचने का मुख्य कारण क्रॉस-एनवायरनमेंट स्थिरता है। यदि आप एक ऐसा पैकेज शिप करते हैं जो bundler कॉन्फिगरेशन के बिना browser और Node.js दोनों में चलता है, Buffer को एनवायरनमेंट डिटेक्शन की आवश्यकता है और atob() को TextDecoder workaround की आवश्यकता है। js-base64 (100M+ साप्ताहिक npm डाउनलोड) दोनों को पारदर्शी रूप से संभालता है।
npm install js-base64 # or pnpm add js-base64
import { fromBase64, fromBase64Url, isValid } from 'js-base64'
// Standard decoding — Unicode-safe, works in browser and Node.js
const raw = fromBase64('eyJldmVudElkIjoiZXZ0XzdjM2E5ZjFiMmQiLCJ0eXBlIjoiY2hlY2tvdXRfY29tcGxldGVkIiwiY3VycmVuY3kiOiJFVVIiLCJhbW91bnQiOjE0OTAwfQ==')
const event = JSON.parse(raw)
console.log(event.type) // checkout_completed
console.log(event.currency) // EUR
// URL-safe decoding — no manual character replacement needed
const jwtPayload = fromBase64Url('eyJ1c2VySWQiOiJ1c3JfOWYyYTFjM2U4YjRkIiwicm9sZSI6ImVkaXRvciJ9')
const claims = JSON.parse(jwtPayload)
console.log(claims.role) // editor
// Validate before decoding untrusted input
const untrusted = 'not!valid@base64#'
if (!isValid(untrusted)) {
console.error('Rejected: invalid Base64 input')
}
// Binary output — second argument true returns Uint8Array
const pngBytes = fromBase64('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', true)
console.log(pngBytes instanceof Uint8Array) // trueSyntax Highlighting के साथ Terminal आउटपुट
CLI डीबगिंग टूल या इंस्पेक्शन स्क्रिप्ट लिखते समय, बड़े JSON पेलोड के लिए सादा console.log आउटपुट पढ़ना मुश्किल होता है। chalk (terminal कलरिंग के लिए सबसे अधिक डाउनलोड किया गया npm पैकेज) Base64 डिकोडिंग के साथ संयुक्त पठनीय, स्कैन करने योग्य terminal आउटपुट उत्पन्न करता है — JWT इंस्पेक्शन, API response डीबगिंग, और कॉन्फिग ऑडिटिंग के लिए उपयोगी।
npm install chalk # chalk v5+ is ESM-only — use import, not require
import chalk from 'chalk'
// Decode and display any Base64 value with smart type detection
function inspectBase64(encoded: string, label = 'Decoded value'): void {
let decoded: string
try {
decoded = Buffer.from(encoded.trim(), 'base64').toString('utf8')
} catch {
console.error(chalk.red('✗ Invalid Base64 input'))
return
}
console.log(chalk.bold.cyan(`\n── ${label} ──`))
// Attempt JSON pretty-print
try {
const parsed = JSON.parse(decoded)
console.log(chalk.green('Type:'), chalk.yellow('JSON'))
for (const [key, value] of Object.entries(parsed)) {
const display = typeof value === 'object' ? JSON.stringify(value) : String(value)
console.log(chalk.green(` ${key}:`), chalk.white(display))
}
return
} catch { /* not JSON */ }
// Plain text fallback
console.log(chalk.green('Type:'), chalk.yellow('text'))
console.log(chalk.white(decoded))
}
// Inspect a Base64-encoded JWT payload
const tokenParts = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c3JfOWYyYTFjM2U4YjRkIiwicm9sZSI6ImVkaXRvciIsImV4cCI6MTcxNzIwMzYwMH0.SIGNATURE'.split('.')
inspectBase64(tokenParts[0], 'JWT Header')
inspectBase64(tokenParts[1], 'JWT Payload')
// ── JWT Header ──
// Type: JSON
// alg: HS256
// typ: JWT
//
// ── JWT Payload ──
// Type: JSON
// userId: usr_9f2a1c3e8b4d
// role: editor
// exp: 1717203600Node.js Streams से बड़ी Base64 फ़ाइलें डिकोड करें
जब Base64-एनकोडेड फ़ाइल ~50 MB से अधिक हो जाती है, readFileSync() के साथ इसे पूरी तरह मेमोरी में लोड करना एक समस्या बन जाती है। Node.js streams आपको डेटा को chunks में डिकोड करने देते हैं — लेकिन Base64 को chunk boundaries पर padding error से बचने के लिए प्रति chunk 4 वर्णों के गुणक की आवश्यकता है (प्रत्येक 4-char समूह ठीक 3 बाइट डिकोड करता है)।
import { createReadStream, createWriteStream } from 'node:fs'
import { pipeline } from 'node:stream/promises'
async function streamDecodeBase64(inputPath: string, outputPath: string): Promise<void> {
const readStream = createReadStream(inputPath, { encoding: 'utf8', highWaterMark: 4 * 1024 * 192 })
const writeStream = createWriteStream(outputPath)
let buffer = ''
await pipeline(
readStream,
async function* (source) {
for await (const chunk of source) {
buffer += (chunk as string).replace(/\s/g, '') // strip any whitespace/newlines
// Decode only complete 4-char groups to avoid mid-stream padding issues
const remainder = buffer.length % 4
const safe = buffer.slice(0, buffer.length - remainder)
buffer = buffer.slice(buffer.length - remainder)
if (safe.length > 0) yield Buffer.from(safe, 'base64')
}
if (buffer.length > 0) yield Buffer.from(buffer, 'base64')
},
writeStream,
)
}
// Decode a 200 MB video that was stored as Base64
await streamDecodeBase64('./uploads/product-demo.b64', './dist/product-demo.mp4')
console.log('Stream decode complete')4 × 1024 × 192 = 786,432 वर्ण (768 KB) उपयोग करता है। 50 MB से कम फ़ाइलों के लिए, readFile() + Buffer.from(content.trim(), 'base64') सरल और पर्याप्त तेज़ है।सामान्य गलतियाँ
मैंने JavaScript कोडबेस में इन चार गलतियों को बार-बार देखा है — ये प्रोडक्शन में डिकोडिंग पथ तक पहुँचने वाले गैर-ASCII वर्ण या लाइन-रैप्ड API प्रतिक्रिया तक छुपी रहती हैं।
गलती 1 — UTF-8 कंटेंट के लिए TextDecoder के बिना atob() का उपयोग करना
समस्या: atob() एक binary string लौटाता है जहाँ प्रत्येक वर्ण एक raw बाइट वैल्यू है। UTF-8 मल्टी-बाइट सीक्वेंस (Cyrillic, CJK, एक्सेंटेड वर्ण) टूटे हुए Latin-1 वर्णों के रूप में दिखाई देते हैं। सुधार: आउटपुट को TextDecoder में रैप करें।
// ❌ atob() returns the raw UTF-8 bytes as a Latin-1 string const encoded = '0JDQu9C10LrRgdC10Lkg0JjQstCw0L3QvtCy' const decoded = atob(encoded) console.log(decoded) // "Алексей Р˜РІР°РЅРѕРІ" ← wrong
// ✅ Use TextDecoder to correctly interpret the UTF-8 bytes const encoded = '0JDQu9C10LrRgdC10Lkg0JjQstCw0L3QvtCy' const binary = atob(encoded) const bytes = Uint8Array.from(binary, ch => ch.charCodeAt(0)) const decoded = new TextDecoder().decode(bytes) console.log(decoded) // Алексей Иванов ✓
गलती 2 — URL-safe Base64 को सीधे atob() में पास करना
समस्या: JWT सेगमेंट + और / की जगह - और _ का उपयोग करते हैं, बिना padding के। atob() गलत डेटा लौटा सकता है या throw कर सकता है। सुधार: पहले मानक वर्ण पुनर्स्थापित करें और padding पुनः जोड़ें।
// ❌ URL-safe JWT segment passed directly — unreliable const jwtPayload = 'eyJ1c2VySWQiOiJ1c3JfOWYyYTFjM2UifQ' const decoded = atob(jwtPayload) // May produce wrong result or throw
// ✅ Restore standard Base64 chars 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)
const bin = atob(pad)
const bytes = Uint8Array.from(bin, ch => ch.charCodeAt(0))
return new TextDecoder().decode(bytes)
}
const decoded = decodeBase64Url('eyJ1c2VySWQiOiJ1c3JfOWYyYTFjM2UifQ')
// {"userId":"usr_9f2a1c3e"} ✓गलती 3 — लाइन-रैप्ड Base64 से newline न हटाना
समस्या: GitHub Contents API और MIME एनकोडर Base64 आउटपुट को 60–76 वर्ण प्रति लाइन रैप करते हैं। atob() \n वर्णों पर InvalidCharacterError थ्रो करता है। सुधार: डिकोड करने से पहले सभी व्हाइटस्पेस हटाएं।
// ❌ GitHub API content field contains embedded newlines const data = await res.json() const decoded = atob(data.content) // ❌ throws InvalidCharacterError
// ✅ Strip newlines (and any other whitespace) before decoding const data = await res.json() const clean = data.content.replace(/\s/g, '') const decoded = atob(clean) // ✓
गलती 4 — डिकोड किए गए बाइनरी कंटेंट पर .toString() कॉल करना
समस्या: जब मूल डेटा बाइनरी (images, PDFs, audio) है, .toString('utf8') कॉल करने से अज्ञात बाइट सीक्वेंस U+FFFD से बदल जाते हैं, चुपचाप आउटपुट दूषित होता है। सुधार: परिणाम को Buffer के रूप में रखें — स्ट्रिंग में कनवर्ट न करें।
// ❌ .toString('utf8') corrupts binary content
import { readFileSync, writeFileSync } from 'node:fs'
const encoded = readFileSync('./uploads/invoice.b64', 'utf8').trim()
const corrupted = Buffer.from(encoded, 'base64').toString('utf8') // ❌
writeFileSync('./out/invoice.pdf', corrupted) // ❌ unreadable PDF// ✅ Keep the Buffer as binary — do not convert to a string
import { readFileSync, writeFileSync } from 'node:fs'
const encoded = readFileSync('./uploads/invoice.b64', 'utf8').trim()
const binary = Buffer.from(encoded, 'base64') // ✓ raw bytes preserved
writeFileSync('./out/invoice.pdf', binary) // ✓ valid PDFJavaScript Base64 डिकोडिंग विधियाँ — त्वरित तुलना
| विधि | UTF-8 आउटपुट | बाइनरी आउटपुट | URL-safe | वातावरण | इंस्टॉल आवश्यक |
|---|---|---|---|---|---|
| atob() | ❌ TextDecoder आवश्यक | ✅ binary string | ❌ मैन्युअल पुनर्स्थापना | Browser, Node 16+, Bun, Deno | नहीं |
| TextDecoder + atob() | ✅ UTF-8 | ✅ Uint8Array के माध्यम से | ❌ मैन्युअल पुनर्स्थापना | Browser, Node 16+, Deno | नहीं |
| Buffer.from().toString() | ✅ utf8 | ✅ Buffer के रूप में रखें | ✅ base64url (Node 18+) | Node.js, Bun | नहीं |
| Uint8Array.fromBase64() (TC39) | ✅ TextDecoder के माध्यम से | ✅ native | ✅ alphabet विकल्प | Chrome 130+, Node 22+ | नहीं |
| js-base64 | ✅ हमेशा | ✅ Uint8Array | ✅ बिल्ट-इन | Universal | npm install |
atob() केवल तभी चुनें जब डिकोड किया गया कंटेंट ASCII टेक्स्ट होने की गारंटी हो। browser में किसी भी उपयोगकर्ता-प्रदत्त या बहु-भाषा टेक्स्ट के लिए, TextDecoder + atob() उपयोग करें। Node.js server-side कोड के लिए, Buffer सही डिफ़ॉल्ट है — यह UTF-8 को स्वचालित रूप से संभालता है और बाइनरी डेटा को बरकरार रखता है। क्रॉस-एनवायरनमेंट libraries के लिए, js-base64 सभी edge cases हटा देता है।
अक्सर पूछे जाने वाले प्रश्न
संबंधित टूल
बिना कोई कोड लिखे एक-क्लिक डिकोड के लिए, अपनी Base64 स्ट्रिंग सीधे Base64 डिकोडर में पेस्ट करें — यह आपके browser में तुरंत मानक और 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.