UNPKG

12.7 kBMarkdownView Raw
1# NATS - Node.js Client
2
3A [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).
4
5[![license](https://img.shields.io/github/license/nats-io/node-nats.svg)](https://www.apache.org/licenses/LICENSE-2.0)
6[![Build Status](https://travis-ci.org/nats-io/node-nats.svg?branch=master)](https://travis-ci.org/nats-io/node-nats)
7[![Coveralls](https://img.shields.io/coveralls/github/nats-io/node-nats/master.svg)](https://coveralls.io/r/nats-io/node-nats?branch=master)
8[![npm](https://img.shields.io/npm/v/nats.svg)](https://www.npmjs.com/package/nats)
9[![npm](https://img.shields.io/npm/dm/nats.svg)](https://www.npmjs.com/package/nats)
10
11## Installation
12
13```bash
14npm install nats
15```
16
17## Basic Usage
18
19```javascript
20var NATS = require('nats');
21var nats = NATS.connect();
22
23// Simple Publisher
24nats.publish('foo', 'Hello World!');
25
26// Simple Subscriber
27nats.subscribe('foo', function(msg) {
28 console.log('Received a message: ' + msg);
29});
30
31// Unsubscribing
32var sid = nats.subscribe('foo', function(msg) {});
33nats.unsubscribe(sid);
34
35// Request Streams
36var sid = nats.request('request', function(response) {
37 console.log('Got a response in msg stream: ' + response);
38});
39
40// Request with Auto-Unsubscribe. Will unsubscribe after
41// the first response is received via {'max':1}
42nats.request('help', null, {'max':1}, function(response) {
43 console.log('Got a response for help: ' + response);
44});
45
46
47// Request for single response with timeout.
48nats.requestOne('help', null, {}, 1000, function(response) {
49 // `NATS` is the library.
50 if(response instanceof NATS.NatsError && response.code === NATS.REQ_TIMEOUT) {
51 console.log('Request for help timed out.');
52 return;
53 }
54 console.log('Got a response for help: ' + response);
55});
56
57// Replies
58nats.subscribe('help', function(request, replyTo) {
59 nats.publish(replyTo, 'I can help!');
60});
61
62// Close connection
63nats.close();
64
65```
66
67## Wildcard Subscriptions
68
69```javascript
70
71// "*" matches any token, at any level of the subject.
72nats.subscribe('foo.*.baz', function(msg, reply, subject) {
73 console.log('Msg received on [' + subject + '] : ' + msg);
74});
75
76nats.subscribe('foo.bar.*', function(msg, reply, subject) {
77 console.log('Msg received on [' + subject + '] : ' + msg);
78});
79
80// ">" matches any length of the tail of a subject, and can only be
81// the last token E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz',
82// 'foo.foo.bar.bax.22'
83nats.subscribe('foo.>', function(msg, reply, subject) {
84 console.log('Msg received on [' + subject + '] : ' + msg);
85});
86
87```
88
89## Queue Groups
90
91```javascript
92// All subscriptions with the same queue name will form a queue group.
93// Each message will be delivered to only one subscriber per queue group,
94// queuing semantics. You can have as many queue groups as you wish.
95// Normal subscribers will continue to work as expected.
96nats.subscribe('foo', {'queue':'job.workers'}, function() {
97 received += 1;
98});
99
100```
101## Clustered Usage
102
103```javascript
104var nats = require('nats');
105
106var servers = ['nats://nats.io:4222', 'nats://nats.io:5222', 'nats://nats.io:6222'];
107
108// Randomly connect to a server in the cluster group.
109var nc = nats.connect({'servers': servers});
110
111// currentServer is the URL of the connected server.
112console.log("Connected to " + nc.currentServer.url.host);
113
114// Preserve order when connecting to servers.
115nc = nats.connect({'dontRandomize': true, 'servers':servers});
116
117```
118## TLS
119
120```javascript
121var nats = require('nats');
122var fs = require('fs');
123
124// Simple TLS connect
125var nc = nats.connect({port: TLSPORT, tls: true});
126
127// Overriding and not verifying the server
128var tlsOptions = {
129 rejectUnauthorized: false,
130};
131var nc = nats.connect({port: TLSPORT, tls: tlsOptions});
132// nc.stream.authorized will be false
133
134// Use a specified CA for self-signed server certificates
135var tlsOptions = {
136 ca: [ fs.readFileSync('./test/certs/ca.pem') ]
137};
138var nc = nats.connect({port: TLSPORT, tls: tlsOptions});
139// nc.stream.authorized should be true
140
141// Use a client certificate if the server requires
142var tlsOptions = {
143 key: fs.readFileSync('./test/certs/client-key.pem'),
144 cert: fs.readFileSync('./test/certs/client-cert.pem'),
145 ca: [ fs.readFileSync('./test/certs/ca.pem') ]
146};
147var nc = nats.connect({port: TLSPORT, tls: tlsOptions});
148
149```
150
151## New Authentication (Nkeys and User Credentials)
152See examples for more usage.
153```javascript
154// Simple connect using credentials file. This loads JWT and signing key
155// each time that NATS connects.
156var nc = NATS.connect('connect.ngs.global', NATS.creds("./myid.creds");
157
158// Setting nkey and signing callback directly.
159var nc = NATS.connect(url, {
160 nkey: 'UAH42UG6PV552P5SWLWTBP3H3S5BHAVCO2IEKEXUANJXR75J63RQ5WM6',
161 sigCB: function(nonce) {
162 return sk.sign(nonce);
163 }
164});
165
166// Setting user JWT statically.
167var nc = NATS.connect(url, {
168 userJWT: myJWT,
169 sigCB: function(nonce) {
170 return sk.sign(nonce);
171 }
172});
173
174// Having user JWT be a function that returns the JWT. Can be useful for
175// loading a new JWT.
176var nc = NATS.connect(url, {
177 userJWT: function() {
178 return myJWT;
179 },
180 sigCB: function(nonce) {
181 return sk.sign(nonce);
182 }
183});
184
185```
186
187## Basic Authentication
188```javascript
189
190// Connect with username and password in the url
191var nc = NATS.connect("nats://foo:bar@localhost:4222");
192
193// Connect with username and password inside object
194var nc = NATS.connect({'url':"nats://localhost:4222", 'user':'foo', 'pass':'bar'});
195
196// Connect with token in url
197var nc = NATS.connect("nats://mytoken@localhost:4222");
198
199// Connect with token inside object
200var nc = NATS.connect({'url':"nats://localhost:4222", 'token':'mytoken'});
201
202```
203## Advanced Usage
204
205```javascript
206
207// Publish with closure, callback fires when server has processed the message
208nats.publish('foo', 'You done?', function() {
209 console.log('msg processed!');
210});
211
212// Flush connection to server, callback fires when all messages have
213// been processed.
214nats.flush(function() {
215 console.log('All clear!');
216});
217
218// If you want to make sure NATS yields during the processing
219// of messages, you can use an option to specify a yieldTime in ms.
220// During the processing of the inbound stream, we will yield if we
221// spend more then yieldTime milliseconds processing.
222var nc = nats.connect({port: PORT, yieldTime: 10});
223
224// Timeouts for subscriptions
225var sid = nats.subscribe('foo', function() {
226 received += 1;
227});
228
229// Timeout unless a certain number of messages have been received
230nats.timeout(sid, timeout_ms, expected, function() {
231 timeout = true;
232});
233
234// Auto-unsubscribe after MAX_WANTED messages received
235nats.subscribe('foo', {'max':MAX_WANTED});
236nats.unsubscribe(sid, MAX_WANTED);
237
238// Multiple connections
239var nats = require('nats');
240var nc1 = nats.connect();
241var nc2 = nats.connect();
242
243nc1.subscribe('foo');
244nc2.publish('foo');
245
246// Encodings
247
248// By default messages received will be decoded using UTF8. To change that,
249// set the encoding option on the connection.
250
251nc = nats.connect({'servers':servers, 'encoding': 'ascii'});
252
253
254
255// PreserveBuffers
256
257// To prevent payload conversion from a Buffer to a string, set the
258// preserveBuffers option to true. Message payload return will be a Buffer.
259
260nc = nats.connect({'preserveBuffers': true});
261
262// Reconnect Attempts and Time between reconnects
263
264// By default a NATS connection will try to reconnect to a server 10 times
265// waiting 2 seconds between reconnect attempts. If the maximum number of
266// retries is reached, the client will close the connection.
267// To change the default behaviour specify the max number of connection
268// attempts in `maxReconnectAttempts` (set to -1 to retry forever), and the
269// time in milliseconds between reconnects in `reconnectTimeWait`.
270
271nc = nats.connect({'maxReconnectAttempts': -1, 'reconnectTimeWait': 250});
272
273nc.on('error', function(err) {
274 console.log(err);
275});
276
277nc.on('connect', function(nc) {
278 console.log('connected');
279});
280
281nc.on('disconnect', function() {
282 console.log('disconnect');
283});
284
285nc.on('reconnecting', function() {
286 console.log('reconnecting');
287});
288
289nc.on('reconnect', function(nc) {
290 console.log('reconnect');
291});
292
293nc.on('close', function() {
294 console.log('close');
295});
296
297```
298
299See examples and benchmarks for more information.
300
301## Connect Options
302
303The following is the list of connection options and default values.
304
305| Option | Aliases | Default | Description
306|-------- |--------- |--------- |------------
307| `encoding` | | `"utf8"` | Encoding specified by the client to encode/decode data
308| `json` | | `false` | If true, message payloads are converted to/from JSON
309| `maxPingOut` | | `2` | Max number of pings the client will allow unanswered before rasing a stale connection error
310| `maxReconnectAttempts` | | `10` | Sets the maximun number of reconnect attempts. The value of `-1` specifies no limit
311| `name` | `client` | | Optional client name
312| `noRandomize` | `dontRandomize`, `NoRandomize` | `false` | If set, the order of user-specified servers is randomized.
313| `pass` | `password` | | Sets the password for a connection
314| `pedantic` | | `false` | Turns on strict subject format checks
315| `pingInterval` | | `120000` | Number of milliseconds between client-sent pings
316| `preserveBuffers` | | `false` | If true, data for a message is returned as Buffer
317| `reconnect` | | `true` | If false server will not attempt reconnecting
318| `reconnectTimeWait` | | `2000` | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts
319| `servers` | `urls` | | Array of connection `url`s
320| `tls` | `secure` | `false` | This property can be a boolean or an Object. If true the client requires a TLS connection. If false a non-tls connection is required. The value can also be an object specifying TLS certificate data. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials
321| `token` | | | Sets a authorization token for a connection
322| `url` | `uri` | `"nats://localhost:4222"` | Connection url
323| `useOldRequestStyle` | | `false` | If set to `true` calls to `request()` and `requestOne()` will create an inbox subscription per call.
324| `user` | | | Sets the username for a connection
325| `verbose` | | `false` | Turns on `+OK` protocol acknowledgements
326| `waitOnFirstConnect` | | `false` | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.
327| `yieldTime` | | | If set, processing will yield at least the specified number of milliseconds to IO callbacks before processing inbound messages
328
329
330
331## Supported Node Versions
332
333Our support policy for Nodejs versions follows [Nodejs release support]( https://github.com/nodejs/Release).
334We will support and build node-nats on even-numbered Nodejs versions that are current or in LTS.
335
336
337## License
338
339Unless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.