一、新建User.proto
文件:User.proto
message User {
required string name = 1;
required int32 age = 2;
required int32 sex = 3;
required string msg = 4;
}
二、使用
var fs = require('fs');
var protocolBuffers = require('protocol-buffers');
var Schema = protocolBuffers(fs.readFileSync('./user.proto'));
User = {
init: function() {
},
encode: function(obj) {
var buf = Schema.User.encode(obj);
console.log('长度:%s---buffer:%j',buf.length,buf);
return buf;
},
decode: function(data) {
var obj = Schema.User.decode(data);
return console.log(obj);
}
};
encoded = User.encode({
name :'zhangsan',
age :16,
sex :'1',
msg :'hello world'
});
User.decode(encoded);