Spaces:
Sleeping
Sleeping
File size: 2,820 Bytes
b0fd1a0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | [](https://github.com/Borewit/text-codec/actions/workflows/ci.yml)
[](https://www.npmjs.com/package/@borewit/text-codec)
[](https://npmcharts.com/compare/@borewit/text-codec?interval=30)

[](LICENSE.txt)
# `@borewit/text-codec`
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` / `TextDecoder` is available, it is used.
- All other encodings are implemented by this library.
## Supported encodings
- `utf-8` / `utf8`
- `utf-16le`
- `ascii`
- `latin1` / `iso-8859-1`
- `windows-1252`
These encodings are commonly encountered in metadata formats and legacy text data.
## β¨ Features
- Encoding and decoding utilities
- Lightweight
- Typed API
## π¦ Installation
```sh
npm install @borewit/text-codec
```
# π API Documentation
## `textDecode(bytes, encoding): string`
Decodes 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**
```js
import { textDecode } from "@borewit/text-codec";
const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
const text = textDecode(bytes, "ascii");
console.log(text); // "Hello"
```
## `textEncode(input, encoding): Uint8Array`
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:
```js
import { textEncode } from "@borewit/text-codec";
const bytes = textEncode("Hello", "utf-16le");
console.log(bytes); // Uint8Array([...])
```
## π Licence
This project is licensed under the [MIT License](LICENSE.txt). Feel free to use, modify, and distribute as needed.
|