peer-emitter

acknowledgeable events

npm install peer-emitter
2 downloads in the last week
8 downloads in the last month

peer-emitter

remote events with semantic acks

usage

fire-and-forget events

Works just like a remote event emitter.

send


var emitter = PeerEmitter(duplexStream);
emitter.emit('evt1', arg1, arg2);

receive


var emitter = PeerEmitter(duplexStream);

emitter.on('evt1', function(arg1, arg2) {
  console.log(arg1, arg2);
});

acknowlegded events

Just add a callback

send

Add a callback when emitting the event to make it acknowlegeable.


var emitter = PeerEmitter(duplexStream, { timeout: 1000 });

// using a callback makes the event require to be acknowlegded
emitter.emit('evt1', arg1, arg2, function(timeout) {
  if (timeout)
    console.log('evt1 timedout');
  else
    console.log('evt1 has been acknowlegded by the other end');
});

// you can specify custom timeouts per emit like so
function onAck(timeout) {
  if (timeout)
    console.log('evt1 timedout');
  else
    console.log('evt1 has been acknowlegded by the other end');
}
onAck.timeout = 3000;
emitter.emit('evt2', arg1, arg2, arg3, onAck);

receive

Add one more argument to the event handler to control when the ack is sent.
If you do not use an extra argument, and the event is acknowlegeable, ack is sent after the event handler is called.


var emitter = PeerEmitter(duplexStream);

emitter.on('evt1', function(arg1, arg2, ack) {
  console.log(arg1, arg2);

  // ack must always be called
  ack();
});

acknowlegded streams

make sure everything gets there

readable


var emitter = PeerEmitter(duplexStream);

// Creating a stream need a name for the objects that are sent or
// received so you can have multiple streams over the same emitter
// as long as they have different names.
// Nice names are names of the data types that are transacted.
// e.g. you can have a stream of apples, and a stream of oranges
var readStream = emitter.ReadStream('alpha');

// To ack each item, you will need to write it to an ack stream
var ackStream = readStream.AckStream();

readStream.on('data', function(alphas) {
  ackStream.write(alphas);
});

writable


var emitter = PeerEmitter(duplexStream);

// creating a stream need a name for the objects that are sent or
// received so you can have multiple streams over the same emitter
// as long as they have different names.
var writeStream = emitter.WriteStream('alpha');
s.pipe(writeStream);

// You also may want to extract an acknowledgement stream for the alpha channel
var ackStream = writeStream.AckStream();
ackStream.on('data', handleAck);

function handleAck(o) {
  console.log('%j got delivered', o);
}

// if you want acks, you probably want to know if they fail aswell
var timeoutStream = writeStream.TimeoutStream( { timeout: 6000 } );
timeoutStream.on('data', handleTimeout);

function handleTimeout(o) {
  console.log('%j timed out');
}
npm loves you