如何将protobuf base64字符串解码为js对象

时间:2016-06-07 12:34:50

标签: javascript protocol-buffers protobuf.js

我尝试将protobuf消息从服务器端(base64字符串)解码为javascript对象。用于解码protobuf.js

正如医生所说:

var builder = ProtoBuf.newBuilder({ convertFieldsToCamelCase: true });
var YourMessage = builder.build("YourMessage");
var buffer = ...; // E.g. a buffer received on a WebSocket
var myMessage = YourMessage.decode(buffer);
...
var b64str = ...; // E.g. a string fetched via AJAX
var myMessage = YourMessage.decode64(b64str);

这就是我尝试这样做的方法(data-base64 string):

var proto = dcodeIO.ProtoBuf;
var buffer = dcodeIO.ByteBuffer;
var b = buffer.wrap(data,"binary");
var builder = proto.newBuilder({ convertFieldsToCamelCase: true });
builder.define("Events");
var message = builder.build("Events");
var result = message.decode(b); //also try to decode base64 string - message.decode64(data);

我收到错误

  

decode / decode64 undefined

1 个答案:

答案 0 :(得分:1)

缺少导入原型定义的行,如下所示(其中tests / example1.proto是您的文件名)

ProtoBuf.loadProtoFile("tests/example1.proto", builder);

或从proto字符串加载

ProtoBuf.loadProto(...protoString..., "example1.proto");

如果没有这个,构建器会说undefined,因为没有任何东西可以用

来构建它的定义