protobuf是由google推出的和语言无关和平台无关,可扩展的序列化数据结构协议,类似于XML,但是比XML更小、更快、更简单。protobuf几乎支持当前的大部分语言,当然也支持JavaScript。
JavaScript使用protobuf主要有如下几个步骤:
1、下载一个编译protobuf的js编译器。
https://github.com/protocolbuffers/protobuf/releases
2、准备一个proto文件,personTest.proto
syntax = "proto2";
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
3、使用 " --js_out=import_style=commonjs,binary:." "语句利用protobuf的编译器编译proto文件将会在该目录下生成名为personTest_pb.js的编译后的js文件;
4、该编译文件的使用。
<1>、需要再次将该Js打包,需要一个引入文件require.js,一个打包的browserify.js/webpack等;
npm install require -g
npm install browserify -g
npm install google-protobuf
<2>、然后新建一个打包的js文件,export.js
var address = require('./personTest_pb');
module.exports = {
DataProto: address
}
<3>、然后执行打包命令“browserify exprort.js -o personTest_main.js”,打包完成的js就可以使用了。
<4>、引入js文件使用;
<html>
<head>
<script type="text/javascript" src="./personTest_main.js"></script>
</head>
<body>
protobuf
</body>
<script type="text/javascript">
var person1 = new proto.Person(); //Address对应的就是proto文件中message 名
person1.setName("Tom");
person1.setId("2");
person1.setEmail("xxxxxxxxx@xx.com");
console.log(person1.toObject());//{email: "xxxxxxxxx@xx.com",id: "2",name: "Tom"}
console.log(person1.getName()); //Tom
</script>
</html>
5、protobuf在js中的api,在google-protobuf中查询即可。