Package Exports
- protocol-buffers
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (protocol-buffers) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
protocol-buffers
Encode/decode protocol buffers in node with stream support
npm install protocol-buffers
Usage
Pass in a proto file as a proto2json object or specify the schema using json
Assuming the following test.proto
file exists
message Test {
required float num = 1;
required string payload = 2;
}
var protobuf = require('protocol-buffers');
var proto2json = require('proto2json')
var schema = protobuf(proto2json.parse(fs.readFileSync('test.proto', 'utf-8')));
var buf = schema.encode({
num: 42,
payload: 'hello world'
});
console.log(buf); // should print a buffer
var obj = schema.decode(buf);
console.log(obj); // should print an object similar to above
You can also stream the encoding/decodings
var encoder = schema.createEncodeStream();
encoder.write({
num: 42,
payload: 'hello world'
});
encoder.write({
num: 43,
payload: 'hello another world'
});
...
encoder.on('data', function(buf) {
// buf is a buffer with the encoded object
});
And similarly if you wanted to decode
var decoder = schema.createDecodeStream();
decoder.write(buf);
decoder.on('data', function(obj) {
// obj is an unpacked object
});
Note that each buffer passed to decoder.write
should contain a full protobuf object so make sure
you do some sort of delimiting/length-prefixing first
In addition to passing in a raw proto file you can also specify the schema as JSON
var schema = protobuf([{
name: 'num',
type: 'float'
}, {
name: 'payload',
type: 'bytes'
}, {
name: 'some_nested_thing',
type: 'object',
fields: [{
name: 'another_prop',
type: 'string'
}]
}]);
License
MIT