Node.js
Encode and decode Base64 with Buffer
Use Buffer to convert bytes to Base64 and back. When the original content is text, specify its encoding explicitly at both ends of the round trip.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const original = "hello é";
const encoded = Buffer.from(original, "utf8").toString("base64");
const decoded = Buffer.from(encoded, "base64").toString("utf8");
console.log(decoded === original);
console.log(encoded);How it works
The first conversion encodes the string as UTF-8 bytes. Base64 represents those bytes using ASCII text. Decoding restores bytes before UTF-8 interpretation restores the original string. Binary inputs should remain bytes rather than being coerced to text.
Limits and mistakes
Base64 is not encryption and typically expands data size. Node’s decoder can be permissive about input forms, so add explicit validation if accepting only one canonical representation matters. Keep URL-safe Base64 rules separate from ordinary Base64.
Check the result
Expect true and a Base64 string. Compare recovered bytes for binary fixtures; a text comparison can conceal invalid or replaced byte sequences.
Sources
Reference documentation for the behavior used in this guide: