Node.js URL安全的Base64編碼

由于標(biāo)準(zhǔn)的Base64包含+、/=,直接將標(biāo)準(zhǔn)Base64編碼后的字符串放到url中會(huì)有問題。于是便有URL安全的Base64編碼,該編碼方式把標(biāo)準(zhǔn)Base64中的+變成-,/變成_,并把=去掉,以便可以在URL中使用。

查了下Node.js標(biāo)準(zhǔn)庫中并沒有URL安全的Base64編碼實(shí)現(xiàn),又不想引入第三方的包依賴,參考gist代碼片段,并做了下修復(fù)改進(jìn)如下:

const base64 = exports;

base64.encode = function (unencoded) {
    return Buffer.from(unencoded || '').toString('base64');
};

base64.decode = function (encoded) {
    return Buffer.from(encoded || '', 'base64').toString('utf8');
};

base64.urlEncode = function (unencoded) {
    const encoded = base64.encode(unencoded);
    return encoded.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '');
};

base64.urlDecode = function (encoded) {
    encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');
    while (encoded.length % 4)
        encoded += '=';
    return base64.decode(encoded);
};

參考鏈接:

An extremely simple implementation of base64 encoding / decoding using node.js Buffers (plus url-safe versions) · GitHub

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容