Node.js unicast discovery, master-slave elections and pub/sub.
npm install democracynpm install democracyyarn add democracy``javascript
var Democracy = require('democracy');
// Basic usage of democracy to manager leader and citizen nodes.
var dem = new Democracy({
source: '0.0.0.0:12345',
peers: ['0.0.0.0:12345', '0.0.0.0:12346', '0.0.0.0:12347'],
});
dem.on('added', (data) => {
console.log('Added: ', data);
});
dem.on('removed', (data) => {
console.log('Removed: ', data);
});
dem.on('elected', (data) => {
console.log('You have been elected leader!');
});
// Support for custom events.
dem.on('ciao', (data) => {
console.log(data.hello); // Logs 'world'
});
dem.send('ciao', {hello: 'world'});
// Support for basic pub/sub.
dem.on('my-channel', (data) => {
console.log(data.hello); // Logs 'world'
});
dem.subscribe('my-channel');
dem.publish('my-channel', {hello: 'world'});
`
javascript
new Democracy({
interval: 1000, // The interval (ms) at which hello heartbeats are sent to the other peers.
timeout: 3000, // How long a peer must go without sending a hello to be considered down.
maxPacketSize: 508, // Maximum size per packet. If the data exceeds this, it will be chunked.
source: '0.0.0.0:12345', // The IP and port to listen to (usually the local IP).
peers: [], // The other servers/ports you want to communicate with (can be on the same or different server).
weight: Math.random() * Date.now(), // The highest weight is used to determine the new leader. Must be unique for each node.
id: 'uuid', // (optional) This is generated automatically with uuid, but can optionally be set. Must be unique for each node.
channels: [], // (optional) Array of channels for this node to listen to (for pub/sub).
});
``#### added
Fired when a new peer has been found.
#### removed
Fired when a peer has gone down and subsequently been removed from the list.
#### leader
Fired when a new leader is selected.
#### elected
Fired on the server that has become the new leader.
#### resigned
Fired on the server that has resigned as the leader.
#### custom/all other events
Fired on all the server except the one that "sent" the event.
Released under the MIT License.