Published on

Base64 Encoding and Decoding with Node.js

Authors

Here's how to do Base64 encoding and decoding using Buffer in Node.js

Encoding

// plain-text string
const str = 'This will be encoded in base64';

// create a buffer
const buff = Buffer.from(str, 'utf-8');

// decode buffer as Base64
const base64 = buff.toString('base64');

// print Base64 string
console.log(base64);  // VGhpcyB3aWxsIGJlIGVuY29kZWQgaW4gYmFzZTY0

Decoding

// Base64 encoded string
const base64 = 'VGhpcyB3aWxsIGJlIGVuY29kZWQgaW4gYmFzZTY0=';

// create a buffer
const buff = Buffer.from(base64, 'base64');

// decode buffer as UTF-8
const str = buff.toString('utf-8');

// print decoded string
console.log(base64);  // This will be encoded in base64

Happy encoding decoding!