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
.
encode / decode base64 with Unicode support
const CODE_EXPRESSION = /%([0-9A-F]{2})/g;
const btoa = (text) => {
return Buffer.from(text, 'binary').toString('base64');
};
const atob = (base64) => {
return Buffer.from(base64, 'base64').toString('binary');
};
const getChar = (part, hex) => {
return String.fromCharCode(parseInt(hex, 16));
};
const encodeUnicode = (text) => {
const safeText = encodeURIComponent(text);
return safeText.replace(CODE_EXPRESSION, getChar);
};
const decodeUnicode = (text) => {
let result = '';
for (let i = 0; i < text.length; ++i) {
const code = text.charCodeAt(i);
result += '%';
if (code < 16) {
result += '0';
}
result += code.toString(16);
}
return decodeURIComponent(result);
};
const Base64 = {
encode: (text) => {
return btoa(encodeUnicode(text));
},
decode: (base64) => {
return decodeUnicode(atob(base64));
},
};
// Example:
console.log(Base64.encode('This is text...')); // VGhpcyBpcyB0ZXh0Li4u
console.log(Base64.decode('VGhpcyBpcyB0ZXh0Li4u')); // This is text...
console.log(Base64.encode('日本')); // 5pel5pys
console.log(Base64.decode('5pel5pys')); // 日本
console.log(Base64.encode('I ❤️ JS')); // SSDinaTvuI8gSlM=
console.log(Base64.decode('SSDinaTvuI8gSlM=')); // I ❤️ JS