### Basic Setup and Teardown Example Source: https://github.com/nats-io/nats.js/blob/main/nst/README.md Demonstrates setting up a JetStream-enabled NATS server and connection for testing, followed by cleanup. Ensure the transport is registered prior to this. ```ts import { cleanup, jetstreamServerConf, setup } from "@nats-io/nst"; import "./connect.ts"; Deno.test("publish/subscribe", async () => { const { ns, nc } = await setup(jetstreamServerConf()); // ... use nc ... await cleanup(ns, nc); }); ``` -------------------------------- ### Install All Workspace Packages with npm Source: https://github.com/nats-io/nats.js/blob/main/CLAUDE.md Install all packages defined in the npm workspaces from the repository root. ```bash npm install --workspaces ``` -------------------------------- ### Running NATS Example in Different Runtimes Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md Commands to execute the NATS client example in Node.js (using tsx), Bun, and Deno. ```bash # Nodejs tsx index.ts # Bun bun index.ts # Deno deno run -A index.ts ``` -------------------------------- ### Install @nats-io/kv via JSR (bunx) Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/media/README.md Install the ESM-only @nats-io/kv library using bunx and the JSR registry. ```bash bunx jsr add @nats-io/kv ``` -------------------------------- ### Object Store Operations Source: https://github.com/nats-io/nats.js/blob/main/obj/README.md Provides examples for common Object Store operations like create, get, put, list, watch, status, seal, and destroy. ```APIDOC ## Object Store Operations ### Create or Bind to an Object Store ```typescript // Create the named ObjectStore or bind to it if it exists: const objm = new Objm(nc); const os = await objm.create("testing", { storage: StorageType.File }); ``` ### Get an Object ```typescript let e = await os.get("hello"); console.log(`hello entry exists? ${e !== null}`); // Access data and potential errors: r?.error.then((err) => { if (err) { console.error("reading the readable stream failed:", err); } }); // Process the data stream: await fromReadableStream(r!.data); ``` ### Put an Object ```typescript // Putting an object returns an info describing the object const info = await os.put({ name: "hello", description: "first entry", options: { max_chunk_size: 1, }, }, readableStreamFrom(sc.encode("hello world"))); console.log( `object size: ${info.size} number of chunks: ${info.size} deleted: ${info.deleted}`, ); ``` ### Watch for Changes ```typescript // watch notifies when a change in the object store happens const watch = await os.watch(); (async () => { for await (const i of watch) { // when asking for history you get a null // that tells you when all the existing values // are provided if (i === null) { continue; } console.log(`watch: ${i!.name} deleted?: ${i!.deleted}`); } })(); ``` ### List Entries ```typescript // list all the entries in the object store // returns the info for each entry const list = await os.list(); list.forEach((i) => { console.log(`list: ${i.name}`); }); ``` ### Get Status ```typescript // you can also get info on the object store as a whole: const status = await os.status(); console.log(`bucket: '${status.bucket}' size in bytes: ${status.size}`); ``` ### Seal Object Store ```typescript // you can prevent additional modifications by sealing it const final = await os.seal(); console.log(`bucket: '${final.bucket}' sealed: ${final.sealed}`); ``` ### Destroy Object Store ```typescript // only other thing that you can do is destroy it // this gets rid of the objectstore const destroyed = await os.destroy(); console.log(`destroyed: ${destroyed}`); ``` ``` -------------------------------- ### Basic NATS Pub/Sub Example Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md A TypeScript example demonstrating connection, subscription, and publishing messages to a NATS server. Includes deferred resolution for asynchronous operations and graceful draining. ```typescript import { connect, deferred, nuid } from "@nats-io/transport-node"; // import { connect, deferred, nuid } from "@nats-io/transport-deno"; const nc = await connect({ servers: "demo.nats.io" }); console.log(`connected`); const subj = nuid.next(); nc.subscribe(subj, { callback: (err, msg) => { console.log(msg.subject, msg.json()); }, }); let i = 0; const d = deferred(); const timer = setInterval(() => { i++; nc.publish(subj, JSON.stringify({ ts: new Date().toISOString(), i })); if (i === 10) { clearInterval(timer); d.resolve(); } }, 1000); await d; await nc.drain(); ``` -------------------------------- ### Install @nats-io/obj with NPM Source: https://github.com/nats-io/nats.js/blob/main/docs/obj/index.html Install the EMS-only version of the library using npm. ```bash npx jsr add @nats-io/obj ``` ```bash yarn dlx jsr add @nats-io/obj ``` ```bash bunx jsr add @nats-io/obj ``` -------------------------------- ### Install @nats-io/nst Source: https://github.com/nats-io/nats.js/blob/main/nst/README.md Install the package as a dev dependency for npm or add it for JSR/Deno. ```sh # npm npm i -D @nats-io/nst # JSR / Deno denp add jsr:@nats-io/nst ``` -------------------------------- ### Install NATS.js Libraries Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md Install the necessary NATS.js core libraries using npm or yarn. ```bash npx jsr add @nats-io/nats-core npx jsr add @nats-io/jetstream npx jsr add @nats-io/kv npx jsr add @nats-io/obj npx jsr add @nats-io/services ``` -------------------------------- ### Import and Initialize Kvm Client Source: https://github.com/nats-io/nats.js/blob/main/docs/kv/index.html Import the Kvm class and initialize it with a NATS connection. This example shows basic usage after importing. ```javascript import { Kvm } from "@nats-io/kv"; // or in node (only when using CJS) // const { Kvm } = require("@nats-io/kv"); // using a nats connection: const kvm = new Kvm(nc); await kvm.list(); await kvm.create("mykv"); ``` -------------------------------- ### Install @nats-io/jetstream via JSR for Bun Source: https://github.com/nats-io/nats.js/blob/main/jetstream/README.md Install the ESM-only version of the library for Bun runtimes. ```bash bunx jsr add @nats-io/jetstream ``` -------------------------------- ### Install @nats-io/kv via JSR (npx) Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/media/README.md Install the ESM-only @nats-io/kv library using npx and the JSR registry. ```bash npx jsr add @nats-io/kv ``` -------------------------------- ### Install @nats-io/jetstream via JSR for Deno Source: https://github.com/nats-io/nats.js/blob/main/jetstream/README.md Install the ESM-only version of the library for Deno runtimes. ```bash deno add jsr:@nats-io/jetstream ``` -------------------------------- ### Install @nats-io/kv via JSR (Deno) Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/media/README.md Install the ESM-only @nats-io/kv library for Deno runtimes using the 'jsr:' specifier. ```bash deno jsr:add @nats-io/kv ``` -------------------------------- ### Install @nats-io/nats-core with NPM Source: https://github.com/nats-io/nats.js/blob/main/core/README.md Use this command to install the Node.js compatible version of the library that supports CJS and ESM. ```bash npm install @nats-io/nats-core ``` -------------------------------- ### Install @nats-io/kv using JSR Source: https://github.com/nats-io/nats.js/blob/main/docs/kv/index.html Install the ESM-only version of the @nats-io/kv library from the JSR registry using deno, npx, yarn dlx, or bunx. ```bash deno jsr:add @nats-io/kv ``` ```bash npx jsr add @nats-io/kv ``` ```bash yarn dlx jsr add @nats-io/kv ``` ```bash bunx jsr add @nats-io/kv ``` -------------------------------- ### Install @nats-io/nats-core with Deno Source: https://github.com/nats-io/nats.js/blob/main/core/README.md Use this command to add the ESM-only version of the library for Deno. ```bash deno add jsr:@nats-io/nats-core ``` -------------------------------- ### Install @nats-io/kv via JSR (yarn dlx) Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/media/README.md Install the ESM-only @nats-io/kv library using yarn dlx and the JSR registry. ```bash yarn dlx jsr add @nats-io/kv ``` -------------------------------- ### Running NATS Client Examples Source: https://github.com/nats-io/nats.js/blob/main/docs/services/media/runtimes.md Commands to execute the NATS client program in Node.js (using tsx), Bun, and Deno. ```bash # Nodejs tsx index.ts # Bun bun index.ts # Deno den o run -A index.ts ``` -------------------------------- ### Set up Node.js Dev Environment Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md Installs the NATS transport for Node.js and the tsx module for running TypeScript files directly. ```bash mkdir -p nats-dev/node cd nats-dev/node npm init esnext -y # the tsx module allows to run typescript files directly by doing `tsx filename.ts` npm install @nats-io/transport-node tsx ``` -------------------------------- ### Install JetStream via JSR Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/index.html Install the JetStream library using various package managers that support JSR. ```bash deno add jsr:@nats-io/jetstream ``` ```bash npx jsr add @nats-io/jetstream ``` ```bash yarn dlx jsr add @nats-io/jetstream ``` ```bash bunx jsr add @nats-io/jetstream ``` -------------------------------- ### NATS WebSocket Connection Example Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md Demonstrates how to establish a WebSocket connection to a NATS server using `wsconnect`. ```typescript import { wsconnect } from "@nats-io/transport-node"; // import { wsconnect } from "@nats-io/transport-deno"; const nc = await wsconnect({ servers: "demo.nats.io:8443" }); ``` -------------------------------- ### Install esbuild for Bundling Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md Install esbuild globally using npm. This command is used for bundling JavaScript applications, including NATS.js. ```bash npm install esbuild --global ``` -------------------------------- ### Install @nats-io/jetstream via JSR for Node.js (npx) Source: https://github.com/nats-io/nats.js/blob/main/jetstream/README.md Install the ESM-only version of the library for Node.js runtimes using npx. ```bash npx jsr add @nats-io/jetstream ``` -------------------------------- ### Publish and Subscribe Example Source: https://github.com/nats-io/nats.js/blob/main/core/README.md Demonstrates basic NATS publish and subscribe functionality. Use this to send and receive string messages. Ensure the NATS server is running and accessible. ```typescript import { connect } from "@nats-io/transport-deno"; // to create a connection to a nats-server: const nc = await connect({ servers: "demo.nats.io:4222" }); // create a simple subscriber and iterate over messages // matching the subscription const sub = nc.subscribe("hello"); (async () => { for await (const m of sub) { console.log(`[${sub.getProcessed()}]: ${m.string()}`); } console.log("subscription closed"); })(); nc.publish("hello", "world"); nc.publish("hello", "again"); // we want to ensure that messages that are in flight // get processed, so we are going to drain the // connection. Drain is the same as close, but makes // sure that all messages in flight get seen // by the iterator. After calling drain, // the connection closes. await nc.drain(); ``` -------------------------------- ### Install @nats-io/obj via NPM Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/media/README-1.md Install the node-only compatible version of the @nats-io/obj library using npm. This version supports both CJS and ESM. ```bash npm install @nats-io/obj ``` -------------------------------- ### Install @nats-io/nats-core with JSR (via bun) Source: https://github.com/nats-io/nats.js/blob/main/core/README.md Use this command to add the ESM-only version of the library for various runtimes using bunx. ```bash bunx jsr add @nats-io/nats-core ``` -------------------------------- ### Per-key TTL on Create Source: https://github.com/nats-io/nats.js/blob/main/kv/README.md Demonstrates setting a Time-To-Live (TTL) for individual keys upon creation. The example shows how the key expires after the specified duration and a PURGE operation is emitted. ```typescript const kv = await new Kvm(js).create("A", { markerTTL: 2_000 }); // per-key TTL is a duration string ("5s", "1m", "1.5h"); minimum 1s await kv.create("k", "hello", "5s"); // deferred can be imported from @nats-io/nats-core const d = deferred(); const now = Date.now(); const iter = await kv.watch(); (async () => { for await (const e of iter) { console.log(Date.now() - now, e.operation, e.key); // ~5s after create the server removes the entry and emits a marker if (e.operation === "PURGE") { d.resolve(); } } })().catch(); await d; // marker itself disappears after the bucket's markerTTL // delay can be imported from @nats-io/nats-core await delay(2500); const e = await kv.get("k"); console.log(e ? "key still found" : "key is gone"); ``` -------------------------------- ### NATS CLI: Making Requests Source: https://github.com/nats-io/nats.js/blob/main/core/README.md Examples of using the NATS CLI to make requests to services. Demonstrates requesting the current time, service uptime, and initiating a service stop. ```bash > nats -s demo.nats.io req time "" 11:39:59 Sending request on "time" 11:39:59 Received with rtt 97.814458ms 2024-06-26T16:39:59.710Z > nats -s demo.nats.io req admin.uptime "" 11:38:41 Sending request on "admin.uptime" 11:38:41 Received with rtt 99.065458ms 61688 >nats -s demo.nats.io req admin.stop "" 11:39:08 Sending request on "admin.stop" 11:39:08 Received with rtt 100.004959ms [admin] #5 stopping.... ``` -------------------------------- ### Key Encoding and Decoding Example Source: https://github.com/nats-io/nats.js/blob/main/docs/kv/types/KvKeyCodec.html Illustrates how keys are encoded and decoded using a KvKeyCodec. Wildcard tokens remain unchanged during the process. This codec is specifically for subject-compatible transformations. ```plaintext // Original key: "users.john.profile"// Encoded key: "dXNlcnM=.am9obg==.cHJvZmlsZQ=="// With wildcards (these remain unchanged):// Original key: "users.*.profile"// Encoded key: "dXNlcnM=.*.cHJvZmlsZQ==" ``` -------------------------------- ### NATS.js Application with Bundled Modules Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md An example application demonstrating how to import and use bundled NATS.js modules to connect to a NATS server and inspect its state. ```javascript import { jetstreamManager, Kvm, Objm, Svcm, wsconnect } from "./nats.mjs"; const nc = await wsconnect({ servers: "demo.nats.io:8443" }); console.log(`connected: ${nc.getServer()}`); const jsm = await jetstreamManager(nc); let streams = 0; for await (const si of jsm.streams.list()) { streams++; } console.log(`found ${streams} streams`); let kvs = 0; const kvm = new Kvm(nc); for await (const k of kvm.list()) { kvs++; } console.log(`${kvs} streams are kvs`); let objs = 0; const objm = new Objm(nc); for await (const k of objm.list()) { objs++; } console.log(`${objs} streams are object stores`); let services = 0; const svm = new Svcm(nc); const c = svm.client(); for await (const s of await c.ping()) { services++; } console.log(`${services} services were found`); await nc.close(); ``` -------------------------------- ### Install @nats-io/nats-core with JSR (via npx) Source: https://github.com/nats-io/nats.js/blob/main/core/README.md Use this command to add the ESM-only version of the library for various runtimes using npx. ```bash npx jsr add @nats-io/nats-core ``` -------------------------------- ### Install @nats-io/nats-core with JSR (via yarn) Source: https://github.com/nats-io/nats.js/blob/main/core/README.md Use this command to add the ESM-only version of the library for various runtimes using yarn dlx. ```bash yarn dlx jsr add @nats-io/nats-core ``` -------------------------------- ### Set up Deno Dev Environment Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md Initializes a Deno project and adds the Deno-specific NATS transport. ```bash mkdir nats-dev/deno cd nats-dev/deno deno init deno add jsr:@nats-io/transport-deno ``` -------------------------------- ### Add Service to NATS Services Framework Source: https://github.com/nats-io/nats.js/blob/main/migration.md Example of adding a service named 'max' with version '0.0.1' to the NATS Services Framework using a NatsConnection instance. Requires '@nats-io/services' to be installed. ```typescript const svc = new Svcm(nc); const service = await svc.add({ name: "max", version: "0.0.1", description: "returns max number in a request", statsHandler, }); ``` -------------------------------- ### Set up Bun Dev Environment Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md Initializes a Bun project and adds the NATS transport for Node.js, which is compatible with Bun. ```bash mkdir nats-dev/bun cd nats-dev/bun bun init -y bun add @nats-io/transport-node ``` -------------------------------- ### Install react-native-worklets for Expo Source: https://github.com/nats-io/nats.js/blob/main/runtimes.md Install react-native-worklets to resolve peer dependency issues with react-native-reanimated in Expo projects. After installation, clear the Metro bundler cache. ```bash npx expo install react-native-worklets npx expo start --clear ``` -------------------------------- ### Set up Deno Dev Environment Source: https://github.com/nats-io/nats.js/blob/main/docs/services/media/runtimes.md Initializes a Deno project and adds the Deno-specific NATS transport package from jsr.io. ```bash mkdir nats-dev/deno cd nats-dev/deno den o init den o add jsr:@nats-io/transport-deno ``` -------------------------------- ### Install NATS Transport for Deno Source: https://github.com/nats-io/nats.js/blob/main/runtimes.md Installs the Deno specific transport for NATS.js using Deno's package manager. Requires Deno to be installed. ```bash mkdir nats-dev/deno cd nats-dev/deno den o init deno add jsr:@nats-io/transport-deno ``` -------------------------------- ### init Source: https://github.com/nats-io/nats.js/blob/main/docs/kv/classes/Bucket.html Initializes the KV bucket with optional configuration. ```APIDOC ## init ### Description Initializes the KV bucket with optional configuration. ### Method init(opts?: Partial): Promise ### Parameters * opts (Partial) - Optional initialization options. ``` -------------------------------- ### Install NATS Packages for React Native Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md Install the necessary NATS packages for a React Native project using Expo. This command installs core, jetstream, kv, and obj modules. ```bash npx create-expo-app@latest npx expo install @nats-io/nats-core @nats-io/jetstream @nats-io/kv @nats-io/obj ``` -------------------------------- ### Initialize JetStream and KV Clients in NATS.js Source: https://github.com/nats-io/nats.js/blob/main/migration.md Demonstrates how to import and initialize the JetStream and Kvm clients. Shows creating a Kvm instance directly or through a JetStream instance, and how to specify JetStream options. ```typescript import { connect } from "@nats-io/transport-deno"; import { jetstream } from "@nats-io/jetstream"; import { Kvm } from "@nats-io/kv"; const nc = await connect(); let kvm = new Kvm(nc); // or create a JetStream which allows you to specify jetstream options const js = jetstream(nc, { timeout: 3000 }); kvm = new Kvm(js); ``` -------------------------------- ### Create, Open, and Manage KV Entries Source: https://github.com/nats-io/nats.js/blob/main/docs/kv/index.html Demonstrates creating a new KV bucket or opening an existing one, creating an entry (which fails if the key exists), and retrieving entry details including operation type and revision. ```javascript // create the named KV or bind to it if it exists: const kvm = new Kvm(nc); const kv = await kvm.create("testing", { history: 5 }); // if the kv is expected to exist: // const kv = await kvm.open("testing"); // create an entry - this is similar to a put, but will fail if the // key exists const hw = await kv.create("hello.world", "hi"); // Values in KV are stored as KvEntries: // { // bucket: string, // key: string, // value: Uint8Array, // created: Date, // revision: number, // delta?: number, // operation: "PUT"|"DEL"|"PURGE" // } // The operation property specifies whether the value was // updated (PUT), deleted (DEL) or purged (PURGE). ``` -------------------------------- ### Initialize Project for esbuild Bundling Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md Create a new directory for your NATS project and initialize it with npm. This sets up the basic project structure for bundling with esbuild. ```bash mkdir mynats cd mynats npm init es6 -y # Adding all the nats libraries here, but you can certainly reference the ones ``` -------------------------------- ### Install @nats-io/jetstream via JSR for Yarn Source: https://github.com/nats-io/nats.js/blob/main/jetstream/README.md Install the ESM-only version of the library for Yarn users. ```bash yarn dlx jsr add @nats-io/jetstream ``` -------------------------------- ### Connect to NATS Servers with Options Source: https://github.com/nats-io/nats.js/blob/main/docs/core/index.html Demonstrates connecting to various NATS servers using different connection options. It shows how to specify servers by hostport, port, or a combination. The example also includes handling connection success and errors, and closing the connection. ```typescript import { connect } from "@nats-io/transport-deno"; const servers = [ {}, { servers: ["demo.nats.io:4442", "demo.nats.io:4222"] }, { servers: "demo.nats.io:4443" }, { port: 4222 }, { servers: "localhost" }, ]; servers.forEach(async (v) => { try { const nc = await connect(v); console.log(`connected to ${nc.getServer()}`); // this promise indicates the client closed const done = nc.closed(); // do something with the connection // close the connection await nc.close(); // check if the close was OK const err = await done; if (err) { console.log(`error closing:`, err); } } catch (_err) { console.log(`error connecting to ${JSON.stringify(v)}`); } }); ``` -------------------------------- ### Customizing JetStream Options for KV Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/media/README.md Shows how to initialize a JetStream client with custom options and then use it to instantiate a Kvm client, inheriting the JetStream configurations. ```typescript import { jetStream } from "@nats-io/jetstream"; import { Kvm } from "@nats-io/kv"; const js = jetStream(nc, { timeout: 10_000 }); // KV will inherit all the options from the JetStream client const kvm = new Kvm(js); ``` -------------------------------- ### Install NATS Node Transport Source: https://github.com/nats-io/nats.js/blob/main/transport-node/README.md Install the NATS Node Transport package using npm or bun. ```bash npm install @nats-io/transport-node # or bun install @nats-io/transport-node ``` -------------------------------- ### Install @nats-io/jetstream via NPM Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/index.html Install the node-only compatible version of the library supporting both CJS and ESM. ```bash npm install @nats-io/jetstream ``` -------------------------------- ### create Source: https://github.com/nats-io/nats.js/blob/main/docs/kv/classes/Kvm.html Creates and opens the specified KV. If the KV already exists, it opens the existing KV. ```APIDOC ## create ### Description Creates and opens the specified KV. If the KV already exists, it opens the existing KV. ### Parameters * **name** (string) - The name of the KV store to create. * **opts** (Partial) - Optional configuration options for the KV store. ### Returns * Promise ``` -------------------------------- ### Initializing Kvm with NATS Connection Source: https://github.com/nats-io/nats.js/blob/main/kv/README.md Instantiate the Kvm client using an existing NATS connection object. Basic operations like listing buckets can be performed immediately. ```javascript // using a nats connection: const kvm = new Kvm(nc); await kvm.list(); await kvm.create("mykv"); ``` -------------------------------- ### Initialize Project for esbuild Bundling Source: https://github.com/nats-io/nats.js/blob/main/docs/obj/media/runtimes.md Initialize a new npm project in a dedicated directory for bundling with esbuild. This sets up the basic project structure and package.json. ```bash mkdir mynats cd mynats npm init es6 -y ``` -------------------------------- ### Creating and Interacting with an Object Store Source: https://github.com/nats-io/nats.js/blob/main/obj/README.md Demonstrates the creation of a named ObjectStore or binding to an existing one, with options for storage type. It also shows how to work with ReadableStreams for handling large data efficiently, and basic operations like getting an entry. ```typescript // create the named ObjectStore or bind to it if it exists: const objm = new Objm(nc); const os = await objm.create("testing", { storage: StorageType.File }); // ReadableStreams allows JavaScript to work with large data without // necessarily keeping it all in memory. // // ObjectStore reads and writes to JetStream via ReadableStreams // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream // You can easily create ReadableStreams from static data or iterators // here's an example of creating a readable stream from static data function readableStreamFrom(data: Uint8Array): ReadableStream { return new ReadableStream({ pull(controller) { // the readable stream adds data controller.enqueue(data); controller.close(); }, }); } // reading from a ReadableStream is similar to working with an async iterator: async function fromReadableStream( rs: ReadableStream, ) { let i = 1; const reader = rs.getReader(); while (true) { const { done, value } = await reader.read(); if (done) { break; } if (value && value.length) { // do something with the accumulated data console.log(`chunk ${i++}: ${sc.decode(value)}`); } } } let e = await os.get("hello"); console.log(`hello entry exists? ${e !== null}`); ``` -------------------------------- ### Build All Workspace Packages with npm Source: https://github.com/nats-io/nats.js/blob/main/CLAUDE.md Build all workspace packages for npm publishing from the repository root. This command is equivalent to `npm run prepack --workspaces`. ```bash npm run build --workspaces ``` -------------------------------- ### Create and Add a Service Source: https://github.com/nats-io/nats.js/blob/main/docs/services/index.html Instantiate a new service with a name, version, and description. Add an endpoint to handle specific requests. ```typescript const svc = new Svc(nc); const service = await svc.add({ name: "max", version: "0.0.1", description: "returns max number in a request", }); // add an endpoint listening on "max" const max = service.addEndpoint("max", (err, msg) => { msg?.respond(); }); ``` -------------------------------- ### Prepack All Workspace Packages with npm Source: https://github.com/nats-io/nats.js/blob/main/CLAUDE.md Run the prepack script for all workspace packages from the repository root. This typically triggers the build process. ```bash npm run prepack --workspaces ``` -------------------------------- ### Objm Initialization Source: https://github.com/nats-io/nats.js/blob/main/obj/README.md Demonstrates how to initialize the Objm client with a NATS connection or a JetStream client. ```APIDOC ## Initialization ### Description Initialize the Objm client with a NATS connection or a pre-configured JetStream client. ### Usage ```javascript import { Objm } from "@nats-io/obj"; // Using a NATS connection: const objm = new Objm(nc); // Using a JetStream client with custom options: import { jetStream } from "@nats-io/jetstream"; const js = jetStream(nc, { timeout: 10_000 }); const objm = new Objm(js); ``` ``` -------------------------------- ### Importing and Initializing JetStream Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/index.html Demonstrates how to import and initialize the JetStream and JetStreamManager clients using a NATS connection. ```APIDOC ## Importing and Initializing JetStream ### Description This section shows how to import the necessary functions from the JetStream library and how to obtain instances of the JetStream and JetStreamManager clients. ### Usage ```javascript // ESM import import { jetstream, jetstreamManager } from "@nats-io/jetstream"; // CommonJS import (Node.js) // const { jetstream, jetstreamManager } = require("@nats-io/jetstream"); // Using a nats connection (nc): const js = jetstream(nc); const jsm = await jetstreamManager(nc); ``` ``` -------------------------------- ### Install @nats-io/kv via NPM Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/media/README.md Install the node-only compatible version of the @nats-io/kv library using npm. This version supports both CommonJS (require) and ECMAScript Modules (import). ```bash npm install @nats-io/kv ``` -------------------------------- ### Create a Key-Value Store with Kvm in NATS.js Source: https://github.com/nats-io/nats.js/blob/main/migration.md Demonstrates how to create a new Key-Value (KV) store with a specified name using the `create()` method on a Kvm instance. ```typescript // To create a KV and open it: await kvm.create("mykv"); ``` -------------------------------- ### getBatch Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/types/DirectStreamAPI.html Retrieves a batch of messages with an optional filter starting at a specific sequence or start time. Note that only a single subject filter is supported. This API is Non-Stable and subject to change. ```APIDOC ## getBatch ### Description Retrieves a batch of messages with an optional filter starting at a specific sequence or start time. Note that only a single subject filter is supported. This API is Non-Stable and subject to change. ### Method getBatch ### Parameters #### Path Parameters - stream (string) - Description not provided - opts (DirectBatchOptions) - Description not provided #### Returns Promise> ``` -------------------------------- ### Install React Native Worklets for Expo Source: https://github.com/nats-io/nats.js/blob/main/docs/core/media/runtimes.md Install react-native-worklets to resolve peer dependency issues with Reanimated 4 in Expo projects. This is necessary for babel-preset-expo to correctly wire up the worklets plugin. ```bash npx expo install react-native-worklets ``` -------------------------------- ### Update, Get, and List KV Entries Source: https://github.com/nats-io/nats.js/blob/main/docs/kv/index.html Update an existing entry, retrieve a specific entry by key, and list all keys in the KV bucket. The get operation returns null if the key is not found. ```javascript // update the entry await kv.put("hello.world", "world"); // retrieve the KvEntry storing the value // returns null if the value is not found const e = await kv.get("hello.world"); // initial value of "hi" was overwritten above 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"}`); ``` -------------------------------- ### List Key-Value Stores with Kvm in NATS.js Source: https://github.com/nats-io/nats.js/blob/main/migration.md Shows how to list all available Key-Value (KV) stores using the `list()` method on a Kvm instance. ```typescript // To list KVs: await kvm.list(); ``` -------------------------------- ### Listing and Getting Object Store Status Source: https://github.com/nats-io/nats.js/blob/main/obj/README.md Shows how to list all entries within an Object Store, retrieving information for each entry. It also demonstrates how to get the overall status of the Object Store, including its bucket name and size in bytes. ```typescript // list all the entries in the object store // returns the info for each entry const list = await os.list(); list.forEach((i) => { console.log(`list: ${i.name}`); }); // you can also get info on the object store as a whole: const status = await os.status(); console.log(`bucket: '${status.bucket}' size in bytes: ${status.size}`); ``` -------------------------------- ### get Source: https://github.com/nats-io/nats.js/blob/main/docs/kv/classes/Bucket.html Retrieves the KvEntry stored under the key, or null if it does not exist. ```APIDOC ## get ### Description Returns the KvEntry stored under the key if it exists or null if not. Note that the entry returned could be marked with a "DEL" or "PURGE" operation which signifies the server stored the value, but it is now deleted. ### Method get(k: string, opts?: { revision: number }): Promise ### Parameters * k (string) - The key of the entry to retrieve. * opts (object) - Optional parameters. * revision (number) - The specific revision of the entry to retrieve. ### Returns Promise - The KvEntry if found, otherwise null. ``` -------------------------------- ### fullKeyName Source: https://github.com/nats-io/nats.js/blob/main/docs/kv/classes/Bucket.html Gets the full name of a key within the bucket. ```APIDOC ## fullKeyName ### Description Gets the full name of a key within the bucket. ### Method fullKeyName(k: string): string ### Parameters * k (string) - The key. ### Returns string - The full key name. ``` -------------------------------- ### Get Stream Information Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/types/Streams.html Retrieves information about a specific stream by its name. ```APIDOC ## get Stream ### Description Retrieves information about a specific stream. ### Method ``` get(stream: string): Promise ``` ### Parameters #### Path Parameters - **stream** (string) - Required - The name of the stream to retrieve. ### Returns - **Promise** - A promise that resolves to a Stream object containing stream details. ``` -------------------------------- ### Get Stream Info using JetStreamManager Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/index.html Retrieve information about a stream by its name. ```javascript const si = await jsm.streams.info(name); ``` -------------------------------- ### Kvm Constructor Source: https://github.com/nats-io/nats.js/blob/main/docs/kv/classes/Kvm.html Creates an instance of the Kv that allows you to create and access KV stores. Note that if the argument is a NatsConnection, default JetStream Options are used. If you want to set some options, please provide a JetStreamClient instead. ```APIDOC ## constructor Kvm ### Description Creates an instance of the Kv that allows you to create and access KV stores. Note that if the argument is a NatsConnection, default JetStream Options are used. If you want to set some options, please provide a JetStreamClient instead. ### Parameters * **nc** (NatsConnection | JetStreamClient) - The NatsConnection or JetStreamClient to use. ### Returns * Kvm ``` -------------------------------- ### noAsyncTraces Source: https://github.com/nats-io/nats.js/blob/main/docs/core/interfaces/ConnectionOptions.html When true, the client will not augment timeout and other error traces with additional context as to where the operation was started. ```APIDOC ## `Optional`noAsyncTraces ### Description When true, the client will not augment timeout and other error traces with additional context as to where the operation was started. ### Type `boolean` ``` -------------------------------- ### Managing KV Store Entries and History Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/media/README.md Provides comprehensive examples of KV operations including creating/opening a bucket, creating/updating/getting/deleting entries, watching for changes, listing keys, and accessing historical data. ```typescript // create the named KV or bind to it if it exists: const kvm = new Kvm(nc); const kv = await kvm.create("testing", { history: 5 }); // if the kv is expected to exist: // const kv = await kvm.open("testing"); // create an entry - this is similar to a put, but will fail if the // key exists const hw = await kv.create("hello.world", "hi"); // Values in KV are stored as KvEntries: // { // bucket: string, // key: string, // value: Uint8Array, // created: Date, // revision: number, // delta?: number, // operation: "PUT"|"DEL"|"PURGE" // } // The operation property specifies whether the value was // updated (PUT), deleted (DEL) or purged (PURGE). // you can monitor values modification in a KV by watching. // You can watch specific key subset or everything. // Watches start with the latest value for each key in the // set of keys being watched - in this case all keys const watch = await kv.watch(); (async () => { for await (const e of watch) { // do something with the change console.log( `watch: ${e.key}: ${e.operation} ${e.value ? e.string() : ""}`, ); } })(); // update the entry await kv.put("hello.world", "world"); // retrieve the KvEntry storing the value // returns null if the value is not found const e = await kv.get("hello.world"); // initial value of "hi" was overwritten above 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) { // do something with the historical value // you can test e.operation for "PUT", "DEL", or "PURGE" // to know if the entry is a marker for a value set // or for a deletion or purge. console.log( `history: ${e.key}: ${e.operation} ${e.value ? sc.decode(e.value) : ""}`, ); } })(); // deletes the key - the delete is recorded await kv.delete("hello.world"); // purge is like delete, but all history values // are dropped and only the purge remains. await kv.purge("hello.world"); // stop the watch operation above watch.stop(); // danger: destroys all values in the KV! await kv.destroy(); ``` -------------------------------- ### Get Consumer Info using JetStreamManager Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/index.html Retrieve the status and configuration of a specific consumer on a stream. ```javascript const ci = await jsm.consumers.info(stream, "me"); console.log(ci); ``` -------------------------------- ### Get Message by Sequence using JetStreamManager Source: https://github.com/nats-io/nats.js/blob/main/docs/jetstream/index.html Retrieve a specific stored message from a stream by its sequence number. ```javascript const sm = await jsm.streams.getMessage(stream, { seq: 1 }); console.log(sm.seq); ``` -------------------------------- ### Publish Messages with Headers Source: https://github.com/nats-io/nats.js/blob/main/docs/core/index.html This example demonstrates how to publish messages with custom headers. Headers are automatically enabled if the server supports them. Ensure both the client and server support headers to avoid errors. ```typescript import { connect, createInbox, Empty, headers } from "../../src/types.ts";import { nuid } from "../../nats-base-client/nuid.ts";const nc = await connect( { servers: `demo.nats.io`, }, ); const subj = createInbox(); const sub = nc.subscribe(subj); (async () => { for await (const m of sub) { if (m.headers) { for (const [key, value] of m.headers) { console.log(`${key}=${value}`); } // reading a header is not case sensitive console.log("id", m.headers.get("id")); } } })().then();// header names can be any printable ASCII character with the exception of `:`.// header values can be any ASCII character except `\r` or `\n`.// see https://www.ietf.org/rfc/rfc822.txtconst h = headers();h.append("id", nuid.next());h.append("unix_time", Date.now().toString());nc.publish(subj, Empty, { headers: h });await nc.flush();await nc.close(); ```