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
.
xxxxxxxxxx
1
const Base64 = {
2
encode: (text) => {
3
const buffer = Buffer.from(text, 'binary');
4
return buffer.toString('base64');
5
},
6
decode: (base64) => {
7
const buffer = Buffer.from(base64, 'base64');
8
return buffer.toString('binary');
9
},
10
};
11
12
// Example:
13
14
console.log(Base64.encode('This is text...')); // VGhpcyBpcyB0ZXh0Li4u
15
console.log(Base64.decode('VGhpcyBpcyB0ZXh0Li4u')); // This is text...