


kv
The kv module implements the NATS KV functionality using JetStream for
JavaScript clients. JetStream clients can use streams to store and access data.
KV is materialized view that presents a different API to interact with the
data stored in a stream using the API for a Key-Value store which should be
familiar to many application developers.
Installation
Note that this library is distributed in two different registries:
- npm a node-specific library supporting CJS (
require
) and ESM (import
) - jsr a node and other ESM (
import
) compatible runtimes (deno, browser, node)
If your application doesn't use require
, you can simply depend on the JSR
version.
NPM
The NPM registry hosts a node-only compatible version of the library
@nats-io/kv supporting both CJS and
ESM:
npm install @nats-io/kv
JSR
The JSR registry hosts the ESM-only @nats-io/kv
version of the library.
deno add @nats-io/kv
npx jsr add @nats-io/kv
yarn dlx jsr add @nats-io/kv
bunx jsr add @nats-io/kv
Referencing the library
Once you import the library, you can reference in your code as:
import { Kvm } from "@nats-io/kv";
const { Kvm } = require("@nats-io/kv");
const kvm = new Kvm(nc);
await kvm.list();
await kvm.create("mykv");
If you want to customize some of the JetStream options when working with KV, you
can:
import { jetStream } from "@nats-io/jetstream";
import { Kvm } from "@nats-io/kv";
const js = jetstream(nc, { timeout: 10_000 });
const kvm = new Kvm(js);
const kvm = new Kvm(nc);
const kv = await kvm.create("testing", { history: 5 });
const hw = await kv.create("hello.world", "hi");
const watch = await kv.watch();
(async () => {
for await (const e of watch) {
console.log(
`watch: ${e.key}: ${e.operation} ${e.value ? e.string() : ""}`,
);
}
})().then();
await kv.put("hello.world", sc.encode("world"));
const e = await kv.get("hello.world");
console.log(`value for get ${e?.string()}`);
const buf: string[] = [];
const keys = await kv.keys();
await (async () => {
for await (const k of keys) {
buf.push(k);
}
})();
console.log(`keys contains hello.world: ${buf[0] === "hello.world"}`);
let h = await kv.history({ key: "hello.world" });
await (async () => {
for await (const e of h) {
console.log(
`history: ${e.key}: ${e.operation} ${e.value ? sc.decode(e.value) : ""}`,
);
}
})();
await kv.delete("hello.world");
await kv.purge("hello.world");
watch.stop();
await kv.destroy();