-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.js
41 lines (34 loc) · 1.21 KB
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const { NatsServerBuilder } = require(`./dist/index`);
const { connect, StringCodec } = require(`nats`);
(async () => {
const server = await NatsServerBuilder.create().build().start();
console.log(`Listen on: `, server.getUrl());
try {
// to create a connection to a nats-server:
const nc = await connect({ servers: server.getUrl() });
// create a codec
const sc = StringCodec();
// 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()}]: ${sc.decode(m.data)}`);
}
console.log(`subscription closed`);
})();
nc.publish(`hello`, sc.encode(`world`));
nc.publish(`hello`, sc.encode(`again`));
// we want to insure 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 on the connection
// the connection closes.
await nc.drain();
} catch (error) {
console.error(error);
} finally {
await server.stop();
}
})();