Languages
[Edit]
EN

Node.js - base64 with Unicode support

1 points
Created by:
Laylah-Walsh
624

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

See also:

  1. Node.js - atob / btoa functions equivalents

  2. Node.js - encoding / decoding base64

Alternative titles

  1. Node.js - base64 with Unicode
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - base64

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join