本机环境Windows 11:
-
首先获取协议编译器并配置到全局环境里,只需要bin文件夹,获取地址: github.com/protocolbuf…
-
创建项目并安装JavaScript协议缓冲区运行库
npm init -y
npm i google-protobuf
- 为了解决protoc-gen-js: program not found or is not executable这个问题,安装下面这个npm包,注意事项如下图。 问题详情:github.com/grpc/grpc-w…
npm i protoc-gen-js
- 项目结构
- 创建jk.helloworld.proto文件
package jk;
message helloworld
{
required int32 id = 1; // ID
required string str = 2; // str
optional int32 opt = 3; //optional field
}
- 生成jk.helloworld_pb.js文件
npm run build
- 创建test.js文件进行测试
let { helloworld } = require("./jk.helloworld_pb");
var hw = new helloworld();
hw.setId(666);
hw.setStr("riko");
console.log(hw);
// Serializes to a UInt8Array.
var bytes = hw.serializeBinary();
var dehw = helloworld.deserializeBinary(bytes);
console.log(dehw);
console.log(dehw.getId());
console.log(dehw.getStr());
const dehwObj = dehw.toObject(); //其实就是调用了一遍get方法
//会输出包含所有属性的一个js对象,没有设置的值就是默认值
console.log(dehwObj);
- 查看输出结果
Ubuntu环境
- 流程同上,一样会遇到第三步中的问题,但提供了另一种解决方案。
'protoc-gen-js' is not recognized as an internal or external command,
operable program or batch file.
--js_out: protoc-gen-js: Plugin failed with status code 1.
以下是评论区提供的方法(需要安装bazel,安装文档bazel.google.cn/install/ubu… ),本人测试后可用
- 测试
把protoc-gen-js复制到你的项目/bin目录里
如上图所示成功生成
protoc --js_out=import_style=commonjs,binary:. --plugin=./bin/protoc-gen-js jk.helloworld.proto
- protobuf-javascript克隆该项目进行测试
- 项目地址:github.com/protocolbuf…
- 本人测试需要在linux进行,需要配置翻墙,需要安装bazel。
- 环境变量配置,同windows,复制protobuf/releases/你下载的包里的bin目录到/usr/local/bin目录下
- 复制protobuf/releases/你下载的包里的include目录到/usr/local/include
- 测试
npm i
PROTOC_INC=/usr/local/include/google/protobuf npm test
参考资料:
- 大佬的文章 www.cnblogs.com/jiayouba/p/…
- google-protobuf www.npmjs.com/package/goo…
- protobuf-javascript github.com/protocolbuf…
- protobuf github.com/protocolbuf…
- issues github.com/grpc/grpc-w…
- issues github.com/protocolbuf…
- 安装使用 forum.cocos.org/t/cocos-cre…