Skip to content

Instantly share code, notes, and snippets.

@aricart
Last active October 26, 2017 13:33
Show Gist options
  • Save aricart/2796171f295fd4bdf59d57a5f2d383e9 to your computer and use it in GitHub Desktop.
Save aricart/2796171f295fd4bdf59d57a5f2d383e9 to your computer and use it in GitHub Desktop.
Test a node-nats connection
'use strict';
var NATS = require('../');
var nc = NATS.connect({maxReconnectAttempts: -1});
nc.on('error', function(e) {
console.error(e);
process.exit();
});
nc.on('disconnect', () => console.log('disconnected'));
nc.on('reconnecting', () => console.log('reconnecting'));
nc.on('close', () => console.log('close'));
nc.on('connect', () => console.log('initial connect'));
// this here for testing by stopping the server/ctrl-Z etc.
setInterval(testConnection, 5000);
// test the connection - by flushing and expecting the flushing
// to be done before some external timeout.
var timeout = null;
function testConnection() {
timeout = setTimeout(function() {
console.log('not connected');
// re-establish your connection
timeout = null;
}, 500);
nc.flush(function() {
if(timeout) {
console.log('connected');
clearTimeout(timeout);
timeout = null;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment