missive
Fast, lightweight library for encoding and decoding JSON messages over streams.
Built using fringe
Installing
npm install --save missive
How it works
Rather than simply using newlines to delimit messages, missive
uses the
time-honored tradition of length prefixing. We think this is safer, and it
can also be quite a bit faster.
Examples
Piping data
missive
exports just two functions, encode()
and parse()
. Each returns
an instance of Stream.Transform
.
Both streams pipe Buffer
instances on the way out (like pretty much
all streams), but encode
expects an object to be passed to write
.
let missive = ;// create an encoder streamlet encode = missive;// create a parser streamlet parse = missive; encode; encode; // should log {"hello": "world"}
data
events
Both streams implement standard data
events, which emit Buffer
instances.
let missive = ;let encode = missive;let parse = missive; parse; encode;
message
event
The parse
stream also implements a custom message
event for convenience.
Rather than emitting a Buffer
instance, the message
event emits a parsed
JavaScript object.
let missive = ;let encode = missive;let parse = missive; parse; encode;
Writing to sockets
let net = ;let missive = ;let server = net; server; server;
Reading from sockets
let net = ;let missive = ;let client = net; client;
Compression
To enable Node's zlib
compression, instantiate an encode
stream
with { deflate: true }
and a parse
stream with { inflate: true }
Note that this will incur a fairly substantial performance penalty, so compression is only advised in situations where message volume is low and saving bytes over the wire is critical.
let missive = ;let encode = missive;let parse = missive; parse; encode;
Spec
In case you can't use missive
on one side of a socket, this is
how it encodes data:
- Let
data
be the result ofJSON.stringify( object ) + '\n'
. - Let
header
be the string'JSON'
as a utf-8 string. - Let
byteLength
be the byte length ofdata
as utf-8. - Let
buffer
be a new buffer of lengthbyteLength + 8
. - Write
header
at byte offset0
ofbuffer
as a UInt32LE. - Write
byteLength
at byte offset4
ofbuffer
as a UInt32LE. - Write
data
at byte offset8
ofbuffer
as a utf-8 string.