From d5af559a94f51ee82951e1def5c5c5749dfa290a Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Mon, 18 Jan 2021 13:43:25 +0100 Subject: [PATCH] perf: improve base64url encoding when available in Node.js --- lib/help/base64url.js | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/lib/help/base64url.js b/lib/help/base64url.js index 16d77a0ce3..003ca6d46f 100644 --- a/lib/help/base64url.js +++ b/lib/help/base64url.js @@ -1,13 +1,12 @@ -const fromBase64 = (base64) => { - return base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') -} - -const encode = (input, encoding = 'utf8') => { - return fromBase64(Buffer.from(input, encoding).toString('base64')) -} - -const encodeBuffer = (buf) => { - return fromBase64(buf.toString('base64')) +let encode; +let encodeBuffer; +if (Buffer.isEncoding('base64url')) { + encode = (input, encoding = 'utf8') => Buffer.from(input, encoding).toString('base64url'); + encodeBuffer = (buf) => buf.toString('base64url'); +} else { + const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); + encode = (input, encoding = 'utf8') => fromBase64(Buffer.from(input, encoding).toString('base64')); + encodeBuffer = (buf) => fromBase64(buf.toString('base64')); } const decodeToBuffer = (input) => {