Base64 URL Encoder and Decoder with UTF-8 support – base64url

Category: Javascript | April 12, 2024
Author:supabase-community
Views Total:14 views
Official Page:Go to website
Last Update:April 12, 2024
License:MIT

Preview:

Base64 URL Encoder and Decoder with UTF-8 support – base64url

Description:

Base64url is a lightweight, straightforward TypeScript library that encodes and decodes Base64 URLs for JavaScript strings with comprehensive UTF-8 support.

It can be useful for developers working with JSON Web Tokens (JWTs) or those involved in encoding JavaScript strings to UTF-8 for binary formats.

How to use it:

1. Download the package and import the following modules into your project.

import {
  stringToBase64URL,
  stringFromBase64URL,
  stringToUTF8,
  stringFromUTF8,
} from './src/base64url.ts';

2. To encode a string to Base64 URL, you can use the stringToBase64URL function. And to decode a Base64 URL string back to its original form, you simply call stringFromBase64URL.

stringToBase64URL('CSSScript');
// => Q1NTU2NyaXB0
stringFromBase64URL('Q1NTU2NyaXB0')
// => CSSScript

3. The library also includes functions to handle UTF-8 encoding and decoding.

  • stringToUTF8 allows you to encode a string to UTF-8 bytes, which you can then write to a stream or buffer.
  • stringFromUTF8 enables you to decode a buffer of UTF-8 bytes back into a string.
stringToUTF8("CSSScript", (byte: number) => {
  // console.log(byte)
});
const result: string[] = [];
const state = { utf8seq: 0, codepoint: 0 };
const onCodepoint = (codepoint: number) => {
  result.push(String.fromCodePoint(codepoint));
};
for (let byte of buffer) {
  // buffer holds all the UTF-8 bytes,
  // call this function for each byte
  stringFromUTF8(byte, state, onCodepoint);
}
const string = result.join("");

You Might Be Interested In:


Leave a Reply