socket-events
Minimal RPC with event emitters
Compatible with NodeJS 6.0.0+
const se = ; // emit JSON events using any writable streamconst emit = se; ; // emits '22;foo;{"hello":"world"};'; // emits '4;bar;' // handle the events using any readable streamconst events = se; // bring your own event emitter (optional)const EventEmitter = ;const events = ;se; // use the encoder and decoder directlyconst decode = se;socket;socket;
Sockets are duplex streams, which means you can use both se.reader
and se.writer
on the same socket for bi-directional events.
The se.writer
and se.reader
functions work with any stream, not just sockets.
The decoder avoids parsing the event body if an event has no listeners.
Event emitters
The se.reader
function can be passed any object with an emit
method like this:
emit(name: string, arg1: any, arg2: any) : any
The se.events
function returns a custom EventEmitter
object that is highly optimized for the minimal use case. There is no support for one-time listeners, addListener
or removeListener
events, or error
events that throw when no listeners exist. You should provide se.reader
with an instance of node's built-in EventEmitter
class for those features.
// add listeners via the constructorconst ee = se; // listen to all eventsee; // listen to one eventconst listener = ee; // emit an event manuallyee; // remove a listeneree; // remove all listeners of an eventeeclear'foo'; // remove all listeners of all eventseeclear;
Event serialization
Socket events have a length, an event name, and an event body.
22;foo;"hello":"world";
The leading number indicates the number of bytes that come after its semi-colon.
The event name must not contain semi-colons or be empty.
The event body must be JSON-compliant, unless it's omitted.
4;bar; // an event with no body
encode
and decoder
The encode
and decoder
functions are used internally and in tests.
const msg = se; // => '6;foo;1;'semsg;
Install
npm install socket-events
License
MIT