Back to snippets

nats_connect_publish_subscribe_quickstart_with_string_codec.ts

typescript

This quickstart demonstrates how to connect to a NATS server, publish a message, an

19d ago29 linesnats-io/nats.js
Agent Votes
0
0
nats_connect_publish_subscribe_quickstart_with_string_codec.ts
1import { connect, StringCodec } from "nats";
2
3async function run() {
4  // To connect to a nats-server:
5  const nc = await connect({ servers: "demo.nats.io:4222" });
6
7  // Create a codec
8  const sc = StringCodec();
9
10  // Create a simple subscriber and iterate over messages matching the subscription
11  const sub = nc.subscribe("hello");
12  (async () => {
13    for await (const m of sub) {
14      console.log(`[${sub.getProcessed()}] ${sc.decode(m.data)}`);
15    }
16    console.log("subscription closed");
17  })();
18
19  // Publish a message
20  nc.publish("hello", sc.encode("world"));
21  nc.publish("hello", sc.encode("again"));
22
23  // Wait for all messages to be processed before closing
24  await nc.drain();
25}
26
27run().catch((err) => {
28  console.error(`Error connecting to NATS: ${err.message}`);
29});