Node.js Reference ยท Globals and Console
Node.js atob() and btoa() functions
Reference for atob() and btoa() in Node.js: Base64 conversion of binary strings, the Latin-1 limit, UTF-8 pitfalls and why Buffer is usually the better tool.
btoa(data) encodes a "binary string" (a string whose characters all have code points 0 to 255) as Base64. atob(encoded) decodes a Base64 string back into a binary string. The names mean "binary to ASCII" and "ASCII to binary".
Both come from the web platform and exist in Node.js for compatibility with browser code. In Node.js the Buffer class is the primary tool for Base64, and the Node documentation marks these two as legacy.
btoa('hello'); // 'aGVsbG8=' atob('aGVsbG8='); // 'hello'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
btoa(data: string): string atob(data: string): string
| Name | Description |
|---|---|
data (btoa) |
A string whose characters are all in the range U+0000 to U+00FF. |
data (atob) |
A Base64 string using the standard alphabet (A-Z a-z 0-9 + /). |
Returns: the Base64 text (btoa) or the decoded binary string (atob).
Errors: a DOMException named InvalidCharacterError (code 5) is thrown by btoa for characters above U+00FF, and by atob for characters outside the Base64 alphabet or an impossible length. Calling either function with no argument throws ERR_MISSING_ARGS.
Usage notes
- Binary string, not text. Each character stands for one byte. For Unicode text, encode to UTF-8 bytes first, as in the second example, or the call throws or produces mojibake.
- Forgiving decoding:
atobignores ASCII whitespace and accepts missing=padding, following the web "forgiving-base64" rule. A leftover single character that cannot form a byte is an error. - Standard alphabet only. URL-safe Base64 (
-and_) is rejected byatob; useBuffer.from(s, 'base64url'). Bufferis faster and more capable: it handles bytes directly, supportsbase64url, and avoids creating huge intermediate strings.- Large data:
String.fromCharCode(...bytes)can overflow the call stack for big arrays. Convert in chunks or useBuffer. - Not encryption. Base64 only changes representation; anyone can decode it.
- Both functions are globals since Node.js 16.
Related
TextEncoderandTextDecoder,DOMException,Blob- Lessons: Buffers, Text encoding