Skip to content
UniKVS
Esc
↑↓navigate↵open⌘Jpreview
On this page

@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.

  • name is Memory.
  • isOpen is always true.
  • No open or close.

Install with:

npm install @unikvs/memory
pnpm add @unikvs/memory
yarn add @unikvs/memory
bun add @unikvs/memory
nub add @unikvs/memory
aube add @unikvs/memory

Usage

Memory implements IStorage. Pass it to UniKvs with persist().

import { Memory } from "@unikvs/memory";

Constructor arguments:

PropType
clone?(<T>(value: T) => T) | undefined

Function used to clone data. Uses structuredClone when omitted.

Type(<T>(value: T) => T) | undefined
DefaultstructuredClone

The 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 structuredClone by default. Change it with the constructor clone option.
  • Stream chunks support only Uint8Array<ArrayBuffer>.
  • Streams from getWritable concatenate written chunks and save them on close.
  • Streams from getReadable emit the stored value as a single chunk. Throws InvalidChunkTypeError when the stored value is not a Uint8Array.

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

PropType
keystring

The key being operated on.

Typestring
chunkunknown

The received chunk value.

Typeunknown
chunkTypestring

The type name of the received chunk.

Typestring

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.

Was this page helpful?