EN
Node.js - base64 with Unicode support
1 points
In this short article, we would like to show how to encode text to base64 and back (decode base64) in Node.js with Unicode support
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 CODE_EXPRESSION = /%([0-9A-F]{2})/g;
2
3
const btoa = (text) => {
4
return Buffer.from(text, 'binary').toString('base64');
5
};
6
7
const atob = (base64) => {
8
return Buffer.from(base64, 'base64').toString('binary');
9
};
10
11
const getChar = (part, hex) => {
12
return String.fromCharCode(parseInt(hex, 16));
13
};
14
15
const encodeUnicode = (text) => {
16
const safeText = encodeURIComponent(text);
17
return safeText.replace(CODE_EXPRESSION, getChar);
18
};
19
20
const decodeUnicode = (text) => {
21
let result = '';
22
for (let i = 0; i < text.length; ++i) {
23
const code = text.charCodeAt(i);
24
result += '%';
25
if (code < 16) {
26
result += '0';
27
}
28
result += code.toString(16);
29
}
30
return decodeURIComponent(result);
31
};
32
33
const Base64 = {
34
encode: (text) => {
35
return btoa(encodeUnicode(text));
36
},
37
decode: (base64) => {
38
return decodeUnicode(atob(base64));
39
},
40
};
41
42
// Example:
43
44
console.log(Base64.encode('This is text...')); // VGhpcyBpcyB0ZXh0Li4u
45
console.log(Base64.decode('VGhpcyBpcyB0ZXh0Li4u')); // This is text...
46
47
console.log(Base64.encode('日本')); // 5pel5pys
48
console.log(Base64.decode('5pel5pys')); // 日本
49
50
console.log(Base64.encode('I ❤️ JS')); // SSDinaTvuI8gSlM=
51
console.log(Base64.decode('SSDinaTvuI8gSlM=')); // I ❤️ JS