提取protobuf定義文件結構


 

先安裝protobuf的js支持包

npm install protobufjs

test.proto文件如下所示

syntax = "proto3";

package Test;

service Serv {
    rpc ApiOne (ServOneRequest ) returns (stream ServOneReply) {};
}
service ServTwo{
    rpc ApiTwo(ServTwoRequest)returns(ServTwoReply){};
}
message ServOneRequest{
    string SyllabusID=1; } message ServOneReply{ string SyllabusID=1; } message ServTwoRequest{ repeated string Id=1; } message ServTwoReply{ EnumV EnumDemo=1; } enum EnumV { no = 0; yes = 1; }

 

 load方法用於加載proto文件

var protobuf = require("protobufjs");
protobuf.load('F:/node-demo/test.proto', function (err, root) {
//....
})

root對象:

上圖中Test命名空間對應proto中的package Test

展開Test對象

 

 

 Test對象包含文件的所有信息,如文件地址,服務,接口,message等nestedArrar包含文件內的所有結構(我粗略的理解為所有頂層的定義都在nestedArrar對象中),在這個對象中Service表示服務,Type表示message,Enum表示枚舉,如需確定子元素具體類型可以從原型拿到,如

 root.Test.nestedArray[0].__proto__.constructor.className
//Service

 

 繼續向下查找包括具體的字段名字段屬性,name,類型等都在里邊這里就不一一展示了。

------------------分割線---------------------------------

提取注釋

看了一上午官方文檔終於找到了提取文件中注釋的方法,上圖中每個消息、服務、字段等等屬性里都有一個comment字段用於存放注釋,注釋編寫規范為/**注釋文本*/,官方規范說支持C/C++注釋原文如下

有興趣的朋友可以去測試一下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM