The `utf8.js` package, currently at its stable version 3.0.0 (last updated in late 2017), provides a comprehensively tested and robust JavaScript implementation for encoding and decoding UTF-8 strings. It distinguishes itself by strictly adhering to the Encoding Standard, ensuring precise handling of all scalar Unicode code point values. A core aspect of its design is strict error handling: the library explicitly throws an `Error` when attempting to encode non-scalar values (such as lone surrogates) or when encountering malformed UTF-8 data during decoding. This approach prioritizes data integrity over silent error correction. For developers requiring the ability to encode or decode non-scalar values, the related `WTF-8` library is recommended. Given its foundational utility and mature status, the project is considered to be in maintenance mode, receiving updates primarily for critical issues rather than frequent feature additions.
npm install utf8Verified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to encode and decode UTF-8 strings, including those with multi-byte Unicode characters, and how to check the library's version.
Ensure input strings are 'well-formed' Unicode. Pre-process strings to remove or replace lone surrogates (e.g., with `U+FFFD` replacement character) before calling `utf8.encode()`. For scenarios requiring encoding of non-scalar values, consider using the `WTF-8` library.
Verify the source of the input `byteString` to ensure it is correctly encoded as UTF-8. Implement robust error handling using `try...catch` blocks around `utf8.decode()` calls to gracefully manage potentially malformed input, or pre-validate the input if possible.
Validate and sanitize input strings to ensure they are well-formed Unicode before passing them to `utf8.encode()`. You can replace lone surrogates or use `String.prototype.toWellFormed()` (if targeting environments that support it) or related libraries.
Check the origin and integrity of the byte string being decoded. Ensure it has been correctly encoded as UTF-8. Wrap `utf8.decode()` calls in a `try...catch` block to handle invalid input gracefully, e.g., by logging the error and using a fallback or replacement.
For Node.js, ensure you use `const utf8 = require('utf8');` in CommonJS modules (`.js` files where `"type": "module"` is not set or in `.cjs` files). If working in an ES module environment (`.mjs` files or `"type": "module"` in `package.json`), you may need to use dynamic `import('utf8')` or rely on a bundler like Webpack or Rollup to handle the CommonJS dependency.No dependency data recorded yet.