javascript下的google-protobuf

482 阅读2分钟

本机环境Windows 11:

  1. 首先获取协议编译器并配置到全局环境里,只需要bin文件夹,获取地址: github.com/protocolbuf… image.png

  2. 创建项目并安装JavaScript协议缓冲区运行库

npm init -y
npm i google-protobuf
  1. 为了解决protoc-gen-js: program not found or is not executable这个问题,安装下面这个npm包,注意事项如下图。 问题详情:github.com/grpc/grpc-w…
npm i protoc-gen-js

image.png

  1. 项目结构 image.png
  • 创建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);

  • 查看输出结果

image.png

Ubuntu环境

  1. 流程同上,一样会遇到第三步中的问题,但提供了另一种解决方案。
'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… ),本人测试后可用

image.png

  • 测试 image.png

把protoc-gen-js复制到你的项目/bin目录里

image.png

如上图所示成功生成

protoc --js_out=import_style=commonjs,binary:. --plugin=./bin/protoc-gen-js  jk.helloworld.proto
  1. protobuf-javascript克隆该项目进行测试
  • 项目地址:github.com/protocolbuf…
  • 本人测试需要在linux进行,需要配置翻墙,需要安装bazel。
  • 环境变量配置,同windows,复制protobuf/releases/你下载的包里的bin目录到/usr/local/bin目录下

image.png

  • 复制protobuf/releases/你下载的包里的include目录到/usr/local/include

image.png

  • 测试
npm i 
PROTOC_INC=/usr/local/include/google/protobuf npm test

参考资料: