I'm trying to understand, how does the ProtoBuf.js
work?
ProtoBuf - https://github.com/dcodeIO/ProtoBuf.js
My proto file gameSetting.proto
looks like:
message GameSettings {
required string gameName = 1;
repeated Category categories = 2;
}
message Category {
required int32 categoryId = 1;
required string categoryAbbreviation = 2;
required string categoryName = 3;
required string numberInSquad = 4;
required string numberInTeam = 5;
required string captain = 6;
}
Here, I am implementing JavaScript code with decoding and encoding of data:
var ProtoBuf = dcodeIO.ProtoBuf;
var protoURL = '../_doc/protobuf/gameSettings.proto';
var dataURL = '../xmlapi?type=game-settings&competitionid=1&outputtype=text';
var builder = ProtoBuf.loadProtoFile( protoURL, function(err, builder) {
// WE CAN ALSO TRY USING JSON FORMAT FOR THE PROTO FILES:
// https://github.com/dcodeIO/ProtoBuf.js/wiki/Builder#using-json-without-the-proto-parser
// encoding test
var GS_build = builder.build( 'GameSettings' );
var GS = new GS_build({
"gameName": "games Test 2015",
"categories": [{
"categoryId": 1,
"categoryAbbreviation": "GK",
"categoryName": "Goalkeeper",
"numberInSquad": "2-2",
"numberInTeam": "1-1",
"captain": "0-1"
}]
});
// encode various types to test
var GS_buffer = GS.encode();
var GS_base64 = GS.encode64(); // this looks like something to use with AJAX
var GS_arrayBuffer = GS_buffer.toArrayBuffer();
// decoding test
var GS_buffer_decoded = GS_build.decode( GS_buffer );
var GS_buffer_decoded_raw = GS_buffer_decoded.toRaw();
var GS_base64_decoded = GS_build.decode64( GS_base64 );
var GS_base64_decoded_raw = GS_base64_decoded.toRaw();
var GS_arrayBuffer_decoded = GS_build.decode( GS_arrayBuffer );
var GS_arrayBuffer_decoded_raw = GS_arrayBuffer_decoded.toRaw();
// decoding AJAX test
$.get( dataURL, function( data ){
var GS = GS_build.decode( data );
});
});
The code
// encoding test
and// decoding test
- works fine.
But there is some problem in the code:
var GS = GS_build.decode( data )
How can I fix it?
The API here is:
Message.decode(buffer:Uint8Array|ArrayBuffer|Buffer|string, encoding:string=)
with
encoding
only required if buffer is a string. Hence, to be able to decode a chunk of data, you have to make sure that it either is an ArrayBuffer/Uint8Array or, if it is a string, provide the correct encoding.Using jQuery's
$.get
without any options will probably corrupt the data, though.See also: https://github.com/dcodeIO/ProtoBuf.js/wiki/How-to-read-binary-data-in-the-browser-or-under-node.js%3F