Decoding google protocol buffer message to javascript using ProtoBuf.js

I am trying to send a post via MQTT using google protocol buffer in javascript (ProtoBuf.js)

I was able to encode the message using the following code:

var ProtoBuf = dcodeIO.ProtoBuf;
var builder = ProtoBuf.loadProtoFile("./complex.proto"),
Game = builder.build("Game"),
Car = Game.Cars.Car;
var car = new Car({
"model" : "Rusty",
"vendor" : {
            "name" : "Iron Inc.",
           "address" : {
                "country" : "USa"
             }
          },
    "speed" : "FAST"
 });
 var buffer = car.encode();
console.log(buffer);
var messagegpb = buffer.toBuffer();
console.log(messagegpb ); //This prints "ArrayBuffer { byteLength: 29 }"

      

Now for decoding, when I tried the following it just doesn't do anything. I also don't see any logs in the browser.

var dec = builder.build("Game"); //nothing after this line gets executed
var msg = dec.decode(messagegpb);
console.log(msg);

      

This is the link of the .proto file I am using. https://github.com/dcodeIO/ProtoBuf.js/blob/master/tests/complex.proto

Can anyone point me where I am going wrong?

Thanks a ton

+3


source to share


1 answer


Presumably these lines:

var dec = builder.build("Game");
var msg = dec.decode(messagegpb);

      

Should be:



var Game = builder.build("Game");
var msg = Game.Cars.Car.decode(messagegpb);

      

That is, you need to specify what type you are decoding.

Your attempted call probably threw an dec.decode

exception because the method decode

didn't exist. You should have seen these exceptions in the error console, or caught them with try

/ catch

.

+2


source







All Articles