Skip to content

nats

Since v8.0.75

The nats module provides a NATS client for JSH applications. Like the MQTT module, it is event-driven and automatically starts connecting when a Client is created.

Typical usage looks like this.

const nats = require('nats');

Client

NATS client object.

Creation
new Client(options)
Options
OptionTypeDescription
serversString[]NATS server URLs such as nats://127.0.0.1:4222
nameStringConnection name
userStringAuthentication user
passwordStringAuthentication password
tokenStringAuthentication token
noRandomizeBooleanDisable server randomization
noEchoBooleanDisable echo of this client’s published messages
verboseBooleanEnable verbose protocol behavior
pedanticBooleanEnable pedantic protocol checks
allowReconnectBooleanEnable reconnect handling
maxReconnectNumberMaximum reconnect attempts
reconnectWaitNumberReconnect wait in milliseconds
timeoutNumberConnect timeout in milliseconds
drainTimeoutNumberDrain timeout in milliseconds
flusherTimeoutNumberFlush timeout in milliseconds
pingIntervalNumberPing interval in milliseconds
maxPingsOutNumberMaximum outstanding pings
retryOnFailedConnectBooleanRetry when the first connection fails
skipHostLookupBooleanSkip host lookup optimization
Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const nats = require('nats');

const client = new nats.Client({
    servers: ['nats://127.0.0.1:4222'],
    name: 'test-client',
    allowReconnect: true,
    maxReconnect: 10,
    reconnectWait: 2000,
    timeout: 10 * 1000,
});

Properties

config

client.config exposes the parsed native NATS configuration.

Representative fields include:

  • servers
  • name
  • allowReconnect
  • maxReconnect
  • reconnectWait
  • timeout
console.println(client.config.servers);
console.println(client.config.timeout);

Methods

publish()

Publishes a message to a subject.

Syntax
publish(subject, message[, options])
Parameters
  • subject String
  • message String | Uint8Array | Object | Array
  • options Object (optional)

Supported options fields:

OptionTypeDescription
replyStringReply subject for request/reply patterns

Objects and arrays are JSON-encoded before publishing.

Return value

None. Result is delivered by published or error events.

subscribe()

Subscribes to a subject.

Syntax
subscribe(subject[, options])
Parameters
  • subject String
  • options Object (optional)

Supported options fields:

OptionTypeDescription
queueStringQueue group name for queue subscriptions
Return value

None. Result is delivered by subscribed or error events.

close()

Closes the client connection.

Syntax
close()

Events

open

Emitted after the connection is established.

client.on('open', () => { ... })

message

Emitted when a subscribed message is received.

client.on('message', (msg) => { ... })

msg fields:

PropertyTypeDescription
topicStringAlias of the subject for MQTT-style handlers
subjectStringNATS subject
replyStringReply subject for request/reply workflows
payloadStringMessage payload

subscribed

Emitted when the server accepts a subscription.

client.on('subscribed', (subject, reason) => { ... })
  • subject String
  • reason Number

The current implementation uses 1 for successful subscribe acknowledgment.

published

Emitted after a publish request completes.

client.on('published', (subject, reason) => { ... })
  • subject String
  • reason Number

The current implementation uses 0 for successful publish completion.

error

Emitted when connection, subscribe, or publish fails.

client.on('error', (err) => { ... })
  • err Error

close

Emitted when close() is called.

client.on('close', () => { ... })

Basic pub/sub example

 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
const nats = require('nats');

const client = new nats.Client({
    servers: ['nats://127.0.0.1:4222'],
    name: 'test-client',
    timeout: 10 * 1000,
});

client.on('open', () => {
    console.println('Connected');
    client.subscribe('test.subject');
});

client.on('subscribed', (subject, reason) => {
    console.println('Subscribed to:', subject, 'reason:', reason);
    client.publish('test.subject', 'Hello, NATS!');
});

client.on('message', (msg) => {
    console.println('Message received on subject:', msg.subject, 'payload:', msg.payload);
    client.close();
});

client.on('close', () => {
    console.println('Disconnected');
});

Request/reply example

For request/reply workflows, subscribe to a reply subject and publish with options.reply.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const nats = require('nats');

const handler = new nats.Client({
    servers: ['nats://127.0.0.1:4222'],
});
handler.on('open', () => {
    handler.subscribe('request.subject');
});
handler.on('message', (msg) => {
    handler.publish(msg.reply, 'pong');
});

const requester = new nats.Client({
    servers: ['nats://127.0.0.1:4222'],
});
requester.on('open', () => {
    requester.subscribe('reply.subject');
    requester.publish('request.subject', 'ping', { reply: 'reply.subject' });
});
requester.on('message', (msg) => {
    console.println(msg.payload);
    requester.close();
    handler.close();
});

Behavior notes

  • Client starts connecting automatically from the constructor.
  • Queue subscriptions are enabled through subscribe(subject, { queue: 'workers' }).
  • Calling publish() or subscribe() before the connection is open emits an error event.
  • Message payloads are exposed as strings by the current implementation.
Last updated on