From 090daa68b52a19e1a64212918f274b67875bebc8 Mon Sep 17 00:00:00 2001 From: Christoph Diehl <1614333+posidron@users.noreply.github.com> Date: Mon, 14 May 2018 19:49:08 +0200 Subject: [PATCH] Add support for Base64 in NodeJS --- lib/utils/common.js | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/lib/utils/common.js b/lib/utils/common.js index 5df4992..3877221 100644 --- a/lib/utils/common.js +++ b/lib/utils/common.js @@ -41,19 +41,28 @@ class common extends utils { static b64encode (str) { // Unicode safe b64 encoding // https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem - return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, - function toSolidBytes (match, p1) { - // noinspection JSCheckFunctionSignatures - return String.fromCharCode('0x' + p1) - })) + if (process.browser) { + return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, + function toSolidBytes (match, p1) { + // noinspection JSCheckFunctionSignatures + return String.fromCharCode('0x' + p1) + }) + ) + } else { + return Buffer.from(str).toString('base64') + } } static b64decode (str) { // Unicode safe b64 decoding // https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem - return decodeURIComponent(atob(str).split('').map(function (c) { - return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) - }).join('')) + if (process.browser) { + return decodeURIComponent(atob(str).split('').map(function (c) { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) + }).join('')) + } else { + return Buffer.from(str, 'base64').toString('ascii') + } } static uniqueList (list) {