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:
- ```sh
- # ✨ Auto-detect
- npx nypm install undio
- # npm
- npm install undio
- # yarn
- yarn add undio
- # pnpm
- pnpm install undio
- # bun
- bun install undio
- ```
Import:
ESM (Node.js, Bun)
- ```js
- import {} from "undio";
- ```
CommonJS (Legacy Node.js)
- ```js
- const {} = require("undio");
- ```
CDN (Deno, Bun and Browsers)
- ```js
- import {} from "https://esm.sh/undio";
- ```
Auto Convert
Undio automatically detects the input type and uses the proper method to convert it to the expected type.
Example:
- ```ts
- import { detectType, toText, toReadableStream } from "undio";
- // Convert any supported type (auto-detected)
- const string = await toText(value);
- const stream = await toReadableStream(value);
- // "ArrayBuffer" | "Blob"| "DataView" | "NumberArray" | "ReadableStream" | "String" | "Uint8Array";
- const type = detectType(value);
- ```
[!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:
- ```ts
- import { isReadableStream, assertArrayBuffer } from "undio";
- if (isReadableStream(value)) {
- /* do something */
- }
- assertArrayBuffer(value); // Throws an error if value is not ArrayBuffer
- // do something
- ```
探客时代
