Base64 in Node.js with Buffers
You'll learn how to encode and decode Base64 data in Node.js using Buffer methods instead of browser-specific functions.
Why Node.js Uses Buffers for Base64
In the browser, you used btoa() and atob() for Base64 encoding and decoding. Node.js takes a different approach because it has native support for binary data through the Buffer class. Buffers provide a more powerful and flexible way to handle Base64 conversions, especially when working with arbitrary binary data.
Think of it like this: browsers give you a simple calculator (btoa/atob), while Node.js gives you a Swiss Army knife (Buffers) that can handle Base64 along with many other data transformations.
Encoding to Base64
To convert a string to Base64, first create a Buffer from your string, then convert it to Base64:
const text = "Hello, Node.js!";
const buffer = Buffer.from(text, 'utf8');
const base64String = buffer.toString('base64');
console.log(base64String); // "SGVsbG8sIE5vZGUuanMh"
Decoding from Base64
To convert Base64 back to a string, create a Buffer from the Base64 string, then convert to UTF-8:
const base64String = "SGVsbG8sIE5vZGUuanMh";
const buffer = Buffer.from(base64String, 'base64');
const decodedText = buffer.toString('utf8');
console.log(decodedText); // "Hello, Node.js!"
The Pattern
The beauty is in the symmetry: Buffer.from() accepts an encoding parameter to interpret the input, and .toString() accepts an encoding parameter to format the output. You're essentially converting between encodings using Buffers as the intermediate representation.
Key Takeaway: In Node.js, use Buffer.from(str, 'base64') to decode Base64 data and buf.toString('base64') to encode data as Base64—no need for btoa() or atob().