赞
踩
egret的protobuf配置:https://github.com/WanderWang/protobuf-egret/
以下是Nodejs的:
- zzz.proto文件:
- package zzz;
- option optimize_for = LITE_RUNTIME;
- message Account{
- required string accountName = 1; //帐号名
- required string pwd = 2; //帐号密码
- }
- message AccountList{
- required int32 index = 1;
- repeated Account list = 2;
- }
- 方法1:
- var ProtoBufJs = require("protobufjs");
- var root = ProtoBufJs.loadSync("./zzz.proto");
- var AccountList = root.lookupType("zzz.AccountList");
- var Account = root.lookupType("zzz.Account");
- var accountListObj = AccountList.create();
- for(var i = 0; i < 10; i++){
- var accountObj = Account.create();
- accountObj.accountName = "断天涯"+i;
- accountObj.pwd = "密码"+i;
- accountListObj.list.push(accountObj);
- }
- var buffer = AccountList.encode(accountListObj).finish();
- 方法2:
- var ProtoBufJs = require("protobufjs");
- var root = ProtoBufJs.loadSync("./zzz.proto");
- var AccountList = root.lookupType("zzz.AccountList");
- var Account = root.lookupType("zzz.Account");
- var accountObj = Account.fromObject({pwd:"密码666", accountName:"断天涯666"});//直接生成对象
- var accountListObj = AccountList.fromObject({index:"0", list:{accountObj}});//直接生成对象
- var buffer = AccountList.encode(accountListObj).finish();
- 方法3:安装完成protobufjs后,在node_module/.bin/有pbjs.cmd 可以生成对应的proto的js代码;通过.proto生成.js文件,然后使用.js
- a、首先已安装protobufjs
- npm install protobufjs
- b、装完以后,可以用cmd命令导出.js文件和.d.ts文件,对应文件路径自己百度去设置,第一行导出js文件,第二行把导出的js生成对应的.d.ts文件,这样就可以在TS代码中调用了。
- -t -static-module参数,表示选的是静态代码模式。
- -w commonjs表示用什么标准来输出js代码,有各种比如es2015、es5、umd、amd什么的,然而我对js不太熟悉,总之只有commonjs可以执行成功,其他都会报错什么的(.d.ts文件反正我是不需要,白鹭引擎看看需要不)
- 生成.js: pbjs -t static-module -w commonjs -o zzz.js zzz.proto
- 生成.d.ts:pbts -o zzz.d.ts zzz.js
- c、具体使用
- var zzzProto= require("./zzz");
- var accountObj = zzzProto.zzz.Account.create(); //使用zzz.js里文件的方法生成对象
- var accountListObj = zzzProto.zzz.AcountList.create();//使用zzz.js里文件的方法生成对象
- ......和之前的使用方式一样
另外网上看到另一片博客:http://keenwon.com/1304.html的方法,暂时没试成功,待试
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。