undio

⇔ Conventionally and Safely convert between various JavaScript data types

README

⇔ undio


⇔ Conventionally and safely convert between various JavaScript data types.

✅ Features


- Type-safe usage
- Runtime-type safety assertion
- Auto type detection and conversion
- Tree-shakable and compact build
- Leverage runtime native performance (+Bun stream utils)

Usage


Install package:


  1. ```sh
  2. # Auto-detect
  3. npx nypm install undio

  4. # npm
  5. npm install undio

  6. # yarn
  7. yarn add undio

  8. # pnpm
  9. pnpm install undio

  10. # bun
  11. bun install undio
  12. ```


Import:


ESM (Node.js, Bun)

  1. ```js
  2. import {} from "undio";
  3. ```

CommonJS (Legacy Node.js)

  1. ```js
  2. const {} = require("undio");
  3. ```

CDN (Deno, Bun and Browsers)

  1. ```js
  2. import {} from "https://esm.sh/undio";
  3. ```


Auto Convert


Undio automatically detects the input type and uses the proper method to convert it to the expected type.

Example:

  1. ```ts
  2. import { detectType, toText, toReadableStream } from "undio";

  3. // Convert any supported type (auto-detected)
  4. const string = await toText(value);
  5. const stream = await toReadableStream(value);

  6. // "ArrayBuffer" | "Blob"| "DataView" | "NumberArray" | "ReadableStream" | "String" | "Uint8Array";
  7. const type = detectType(value);
  8. ```

[!NOTE]

Because of stream support, the return type can be a promise. Always make sure to use an await before them.


[!NOTE]

Alternatively you can use low-level `To(value)` utils to explicitly convert from one type to another. See all utils section.


Runtime type checking


You can use `is(input) and assert(input)` utils to validate input type.

[!NOTE]

All conversion utilities use assertions for runtime type safety by default, so you don't need to manually do this.


Example:

  1. ```ts
  2. import { isReadableStream, assertArrayBuffer } from "undio";

  3. if (isReadableStream(value)) {
  4.   /* do something */
  5. }

  6. assertArrayBuffer(value); // Throws an error if value is not ArrayBuffer
  7. // do something
  8. ```