@unikvs/opfs
How to use Opfs in @unikvs/opfs, a storage that keeps bytes in OPFS.
Overview
@unikvs/opfs Browser only is a storage that keeps bytes in the Origin Private File System. Use it to persist files in the browser.
nameisOpfs.- Requires
open. Noclose. - Specify the root directory in the constructor.
- This storage validates keys as file names.
Install with:
npm install @unikvs/opfspnpm add @unikvs/opfsyarn add @unikvs/opfsbun add @unikvs/opfsnub add @unikvs/opfsaube add @unikvs/opfsUsage
Opfs implements IStorage. Pass it to UniKvs with persist().
import { Opfs } from "@unikvs/opfs";
Constructor arguments:
PropType
root?string | FileSystemDirectoryHandle
Root directory for data. Pass a name as a string or a directory handle directly.
Type
string | FileSystemDirectoryHandleDefault
".unikvs"The following example stores bytes and reads them back.
import { Opfs } from "@unikvs/opfs";
import * as unikvs from "unikvs";
const kvs = new unikvs.Builder<{
image: unikvs.Value<Uint8Array>;
}>()
.persist(new Opfs())
.build();
await kvs.open();
await kvs.set("image", new Uint8Array([0, 1, 2]));
const bytes = await kvs.get("image");
console.log(bytes); // Uint8Array(3) [0, 1, 2]
await kvs.close();
Data types
| Operation | Supported data type |
|---|---|
write/read |
Uint8Array<ArrayBuffer> |
getWritable/getReadable chunks |
Uint8Array<ArrayBuffer> |
- Stores bytes only.
- This storage validates keys as file names. Invalid keys throw
InvalidFilenameError. - Streams from
getWritablewrite directly to the OPFS write stream. - Streams from
getReadablereturn the file’s read stream.
Errors
This package has no package-specific errors. Invalid keys throw InvalidFilenameError from @unikvs/utils. Reading a missing key throws a NotFoundError DOMException. Operating before opening throws a TypeError.