npm i protobufjs -D
添加两个proto文件
User.proto
syntax = "proto3";
package login;
message PBUser {
string uid = 1;
string pwd = 2;
int64 age = 3;
}
Login.proto
syntax = "proto3";
package login;
import "./User.proto";
message LoginReq {
PBUser user = 1;
}
message LoginRes {
int64 code = 1;
}
package.json 添加脚本, 将proto文件导出为js文件
"proto": "npx pbjs -t json-module -w commonjs -o api/proto/proto.js api/proto/*.proto"
引入导出的js
let protoRoot = require("./proto/proto.js");
let loginReqObj = protoRoot.lookup('login').LoginReq.create();
let user = protoRoot.lookup('login').PBUser.create();
user.uid = "root"
user.pwd = '1234'
user.age = 11
loginReqObj.user = user
let loginReqObjBuffer = protoRoot.lookup('login').LoginReq.encode(loginReqObj).finish();
console.log(loginReqObjBuffer)
let loginReqObj2 = protoRoot.lookup('login').LoginReq.decode(loginReqObjBuffer);
console.log(loginReqObj2)
console.log(loginReqObj2.user.uid, loginReqObj2.user.pwd, loginReqObj2.user.age)
文章来源: www.oschina.net,作者:阿豪boy,版权归原作者所有,如需转载,请联系作者。
原文链接:https://my.oschina.net/ahaoboy/blog/3162055