A browser UTF-8 string <-> UInt8Array converter with automatic fallback between WHATWG Encoding API and pure JavaScript
npx @tessl/cli install tessl/npm-aws-sdk--util-utf8-browser@3.259.0A browser-compatible UTF-8 string encoding and decoding utility that provides automatic fallback between the WHATWG Encoding API and pure JavaScript implementations. This utility ensures cross-browser compatibility for UTF-8 operations in web environments.
npm install @aws-sdk/util-utf8-browserimport { fromUtf8, toUtf8 } from "@aws-sdk/util-utf8-browser";For CommonJS:
const { fromUtf8, toUtf8 } = require("@aws-sdk/util-utf8-browser");import { fromUtf8, toUtf8 } from "@aws-sdk/util-utf8-browser";
// Convert string to UTF-8 byte array
const text = "Hello, World! 🌍";
const bytes = fromUtf8(text);
console.log(bytes); // Uint8Array(15) [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33, 32, 240, 159, 140, 141]
// Convert UTF-8 byte array back to string
const restored = toUtf8(bytes);
console.log(restored); // "Hello, World! 🌍"
// Handle complex Unicode characters including surrogate pairs
const complexText = "🚀💻🌟";
const complexBytes = fromUtf8(complexText);
const restoredComplex = toUtf8(complexBytes);
console.log(restoredComplex === complexText); // true
// Works with international text and scripts
const arabicText = "دستنوشتهها نمیسوزند";
const cyrillicText = "Рукописи не горят";
const arabicBytes = fromUtf8(arabicText);
const cyrillicBytes = fromUtf8(cyrillicText);
console.log(toUtf8(arabicBytes) === arabicText); // true
console.log(toUtf8(cyrillicBytes) === cyrillicText); // trueThe package uses feature detection to automatically select the best available UTF-8 conversion method:
Converts JavaScript strings to UTF-8 encoded byte arrays with automatic implementation selection.
/**
* Converts a JavaScript string to a UTF-8 encoded Uint8Array
* @param input - The string to encode
* @returns UTF-8 encoded byte array
*/
function fromUtf8(input: string): Uint8Array;Implementation Details:
TextEncoder when available for optimal performanceConverts UTF-8 encoded byte arrays back to JavaScript strings with automatic implementation selection.
/**
* Converts a UTF-8 encoded Uint8Array to a JavaScript string
* @param input - The UTF-8 encoded byte array to decode
* @returns Decoded JavaScript string
*/
function toUtf8(input: Uint8Array): string;Implementation Details:
TextDecoder when available for optimal performance// Core functions use native JavaScript types
type Uint8Array = Uint8Array;
type string = string;The functions handle malformed input gracefully:
This package is deprecated in favor of @aws-sdk/util-utf8 which provides unified UTF-8 utilities for both Node.js and browser environments. Consider migrating to the newer package for new projects.