EN
Node.js - encoding / decoding base64
3
points
In this short article, we would like to show how to encode text to base64 and back (decode base64) in Node.js.
Note:
In the presented solution, we use the Buffer class, which has a global scope in Node.js and does not need to be imported using the
require
.
const Base64 = {
encode: (text) => {
const buffer = Buffer.from(text, 'binary');
return buffer.toString('base64');
},
decode: (base64) => {
const buffer = Buffer.from(base64, 'base64');
return buffer.toString('binary');
},
};
// Example:
console.log(Base64.encode('This is text...')); // VGhpcyBpcyB0ZXh0Li4u
console.log(Base64.decode('VGhpcyBpcyB0ZXh0Li4u')); // This is text...