Protobuf 笔记

ProtoBuf.js 使用技巧

在NodeJS中玩转Protocol Buffer

1
2
3
4
5
6
7
// awesome.proto
package awesomepackage;
syntax = "proto3";

message AwesomeMessage {
string awesome_field = 1; // becomes awesomeField
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<html>
<script src="http://cdn.rawgit.com/dcodeIO/protobuf.js/6.7.0/dist/protobuf.js"></script>
<script>
// writing
protobuf.load("awesome.proto", function(err, root) {
if (err)
throw err;

// Obtain a message type
var AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage");

// Exemplary payload
var payload = { awesomeField: "AwesomeString", test:"test" };

// Verify the payload if necessary (i.e. when possibly incomplete or invalid)
var errMsg = AwesomeMessage.verify(payload);
if (errMsg)
throw Error(errMsg);

// Create a new message
var message = AwesomeMessage.fromObject(payload); // or use .fromObject if conversion is necessary

// Encode a message to an Uint8Array (browser) or Buffer (node)
var buffer = AwesomeMessage.encode(message).finish();
// ... do something with buffer

// Decode an Uint8Array (browser) or Buffer (node) to a message
var message = AwesomeMessage.decode(buffer);
// ... do something with message

// If the application uses length-delimited buffers, there is also encodeDelimited and decodeDelimited.

// Maybe convert the message back to a plain object
var object = AwesomeMessage.toObject(message, {
longs: String,
enums: String,
bytes: String,
// see ConversionOptions
});
});
</script>
</html>