记在Windows平台上将proto翻译为JS的一个小坑
研究gRPC的时候,接触到了proto文件,现阶段我觉得这应该是一个可以翻译成各种语言、并且可以使用gRPC进行极其方便的远程调用的描述数据结构的文件。这次记录一下自己的愚蠢行为。
PS: 其实按照官方文档的说法应该是“预生成(pre-generated)”的,我的理解就是翻译过来,新人拙见,还请斧正。
美好的开始
按照官方给的介绍started with gRPC in Node,挂上我的梯子把代码拔下来
1 | $ # Clone the repository to get the example code |
开两个shell让他们表演一下如何传递一个word
1 | $ node greeter_server.js |
1 | $ node greeter_client.js |
警告信息就不管它了,又不是不能用,相关issue#120
然而直接调用proto文件这并不是我想要的,翻译成js才行。
错误
之后,来到另外一个文件夹static_codegen。确认过文件头,*_pb.js就是我想要的翻译结果。如何翻译出来呢?
打开README.MD
This is the static code generation variant of the Node examples. Code in these examples is pre-generated using protoc and the Node gRPC protoc plugin, and the generated code can be found in various
*_pb.jsfiles. The command line sequence for generating those files is as follows (assuming thatprotocandgrpc_node_pluginare present, and starting in the directory which contains this README.md file):
1
2
3
4 cd ../../protos
npm install -g grpc-tools
grpc_tools_node_protoc --js_out=import_style=commonjs,binary:../node/static_codegen/ --grpc_out=../node/static_codegen --plugin=protoc-gen-grpc=`which grpc_tools_node_protoc_plugin` helloworld.proto
grpc_tools_node_protoc --js_out=import_style=commonjs,binary:../node/static_codegen/route_guide/ --grpc_out=../node/static_codegen/route_guide/ --plugin=protoc-gen-grpc=`which grpc_tools_node_protoc_plugin` route_guide.proto
上面的英文渣翻一下
这是静态代码版本的Node程序示例。示例使用protoc工具和Node gRPC protoc插件预生成的代码,这些生成的代码就在各种
* _pb.js文件中。生成这些文件的命令如下(假设protoc和grpc_node_plugin已经安装好了,并且现在正处在包含此README.md文件的目录开始))
按照命令一行一行进行。安装好了grpc-tools包。在将要执行下面的生成命令时我迟疑了一下。
这明明是Linux下的命令,你看这个目录,你看这个which命令。所以,把撇(/)换成捺(\),everthing找一下grpc_tools_node_protoc_plugin文件的位置得到C:\Program Files\node-v10.3.0-win-x64\grpc_tools_node_protoc_plugin,确认了一下,确实应该在PATH中能够被which找到。替换上执行一下
1 | $ grpc_tools_node_protoc --js_out=import_style=commonjs,binary:..\node\static_codegen\ --grpc_out=..\node\static_codegen --plugin=protoc-gen-grpc="C:\Program Files\node-v10.3.0-win-x64\grpc_tools_node_protoc_plugin" helloworld.proto |
一个回车敲下去。
1 | --grpc_out: protoc-gen-grpc: %1 ������Ч�� Win32 Ӧ�ó��� |
Windows喜闻乐见的编码问题,应该能猜到,乱码部分意思应该是:不是有效的 Win32 应用程序。
然后经过一番Google。我发现了一个相似的问题Where to find the protoc grpc plugin for Node.js to run on Windows ?
然后发现他用的是grpc_node_plugineverthing一下,找到C:\Program Files\node-v10.3.0-win-x64\node_modules\grpc-tools\bin\grpc_node_plugin.exe看着这个正常多了,应该是一个Win 32程序了。修改命令如下:
1 | $ grpc_tools_node_protoc --js_out=import_style=commonjs,binary:..\node\static_codegen\ --grpc_out=..\node\static_codegen --plugin=protoc-gen-grpc="C:\Program Files\node-v10.3.0-win-x64\node_modules\grpc-tools\bin\grpc_node_plugin.exe" helloworld.proto |
成功。
后记
被自己蠢死,打开C:\Program Files\node-v10.3.0-win-x64\grpc_tools_node_protoc_plugin看了一下,里面是bash脚本。同时还存在一个C:\Program Files\node-v10.3.0-win-x64\grpc_tools_node_protoc_plugin.cmd如果直接用这个也是可以的。鼓捣了半天还水了一篇博文。
(逃