pbs
Streaming encoder/decoder for protocol buffers
npm install pbs
Usage
var pbs =var messages =// create a streaming encodervar encoder = messagesCompany// create a streaming decodervar decoder = messagesCompany
Encoding
Use pbs to encode a protocol buffers message (no matter how large!) to a stream.
The encoder stream will expose all properties of the protobuf message as methods on the stream that you can pass the value you want to write to.
encoder
The callback is called when the stream has been flushed.
Here is an example using the above protobuf schema:
// all the properties of Company are exposed as methodsvar encoder = messagesCompany// encoder is a readable stream containing the protobuf message.// you can pipe it anywhere!encoder// write a name to the streamencodername'my-company'// write an employee to the streamencoder// write another oneencoder// no more data - will end the readable streamencoder
The encoder stream produces a valid protobuf message that can be decoded with any other parser that follows the protobuf spec.
Decoding
Similar to encoding you can use pbs to decode a protobuf message.
The decoder stream also exposes the properties as methods, but instead of passing a value you pass a function that is called then that property is found in the stream.
decoder
Here is an example using the above schema:
// all the properties of Company are exposes as methodsvar decoder = messagesCompanydecodername {console// done processing}decoderdecoderdecoderfs
Use cases
You can use this to parse large protobuf messages that might not fit in memory.
Another use case is to use this to implement a streaming binary protocol encoder/decoder. Let's say I wanted to implement a chat protocol. I could describe it using the following proto schema:
message ChatProtocol { repeated Message messages = 1; repeated string online = 2; message Message { required string from = 1; required string text = 2; }}
and then just use pbs to parse it:
var fs =var pbs =var messages =var decoder = messagesChatProtocol// read messagesdecoderdecoder// write messagesvar encoder = messagesChatProtocolencoderencoder// setup the pipelineencoder
Since the entire stream is valid protobuf, you could even save it to a file and parse it using another protobuf parser to debug an application.
License
MIT