@unikvs/memory
Usage of Memory in @unikvs/memory, a storage that keeps arbitrary values in memory.
Overview
@unikvs/memory Usage of Memory in @unikvs/memory, a storage that keeps arbitrary values in memory.
nameisMemory.isOpenis alwaystrue.- No
openorclose.
Install with:
npm install @unikvs/memorypnpm add @unikvs/memoryyarn add @unikvs/memorybun add @unikvs/memorynub add @unikvs/memoryaube add @unikvs/memoryUsage
Memory implements IStorage. Pass it to UniKvs with persist().
import { Memory } from "@unikvs/memory";
Constructor arguments:
clone?(<T>(value: T) => T) | undefined
Function used to clone data. Uses structuredClone when omitted.
(<T>(value: T) => T) | undefinedstructuredCloneThe following example stores a value and reads it back.
import { Memory } from "@unikvs/memory";
import * as unikvs from "unikvs";
const kvs = new unikvs.Builder<{
greeting: unikvs.PlainValue<string>;
}>()
.persist(new Memory())
.build();
await kvs.open();
await kvs.set("greeting", "hello");
const value = await kvs.get("greeting");
console.log(value); // "hello"
await kvs.close();
Data types
| Operation | Supported data type |
|---|---|
write / read |
Arbitrary values (strings, objects, etc.) |
getWritable / getReadable chunks |
Uint8Array<ArrayBuffer> |
- Stores arbitrary values. Handles values cloneable with
structuredClone, such as strings and objects. - Clones read/write values with
structuredCloneby default. Change it with the constructorcloneoption. - Stream chunks support only
Uint8Array<ArrayBuffer>. - Streams from
getWritableconcatenate written chunks and save them onclose. - Streams from
getReadableemit the stored value as a single chunk. ThrowsInvalidChunkTypeErrorwhen the stored value is not aUint8Array.
Errors
KeyNotFoundError
Meaning
Thrown when the specified key does not exist. A shared error from @unikvs/core.
How to fix
Check with exists before reading.
Example
The following example catches KeyNotFoundError.
import { KeyNotFoundError } from "@unikvs/memory";
try {
await kvs.get("missing-key");
} catch (ex) {
if (ex instanceof KeyNotFoundError) {
console.log("Key not found");
} else {
throw ex;
}
}
InvalidChunkTypeError
Meaning
Thrown when a non-Uint8Array<ArrayBuffer> chunk is written to a stream, or when getReadable is called on a value that is not a Uint8Array.
How to fix
Write Uint8Array chunks to streams. Store byte sequences for values used with getReadable.