A lightweight polyfill for text encoders and decoders covering a small set of commonly used encodings.
Some JavaScript runtimes provide limited or inconsistent encoding support through TextEncoder and TextDecoder.
Examples include environments like Hermes (React Native) or certain Node.js builds with limited ICU support.
This module provides reliable encode/decode support for a small set of encodings that may be missing or unreliable in those environments.
- If a native UTF-8
TextEncoder/TextDecoderis available, it is used. - All other encodings are implemented by this library.
utf-8/utf8utf-16leasciilatin1/iso-8859-1windows-1252
These encodings are commonly encountered in metadata formats and legacy text data.
- Encoding and decoding utilities
- Lightweight
- Typed API
npm install @borewit/text-codecDecodes binary data into a JavaScript string.
Parameters
bytes(Uint8Array) — The binary data to decode.encoding(SupportedEncoding, optional) — Encoding type. Defaults to"utf-8".
Returns
string— The decoded text.
Example
import { textDecode } from "@borewit/text-codec";
const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
const text = textDecode(bytes, "ascii");
console.log(text); // "Hello"Encodes a JavaScript string into binary form using the specified encoding.
Parameters
input(string) — The string to encode.encoding(SupportedEncoding, optional) — Encoding type. Defaults to"utf-8".
Returns
Uint8Array — The encoded binary data.
Example:
import { textEncode } from "@borewit/text-codec";
const bytes = textEncode("Hello", "utf-16le");
console.log(bytes); // Uint8Array([...])This project is licensed under the MIT License. Feel free to use, modify, and distribute as needed.