Add support for Base64 in NodeJS

This commit is contained in:
Christoph Diehl 2018-05-14 19:49:08 +02:00 committed by GitHub
parent b1908915d5
commit 090daa68b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 17 additions and 8 deletions

View File

@ -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) {