用于 Node.js 的协议缓冲区
协议缓冲区 适用于 Node.js
npm install protocol-buffers假设存在以下 test.proto 文件
enum FOO {
BAR = 1;
}
message Test {
required float num = 1;
required string payload = 2;
}
message AnotherOne {
repeated FOO list = 1;
}使用上述 proto 文件,通过执行以下操作来编码/解码消息:
var protobuf = require('protocol-buffers')
// pass a proto file as a buffer/string or pass a parsed protobuf-schema object
var messages = protobuf(fs.readFileSync('test.proto'))
var buf = messages.Test.encode({
num: 42,
payload: 'hello world'
})
console.log(buf) // should print a buffer要解码消息,请使用 Test.decode
var obj = messages.Test.decode(buf)
console.log(obj) // should print an object similar to above枚举的访问方式与消息相同
var buf = messages.AnotherOne.encode({
list: [
messages.FOO.BAR
]
})嵌套枚举可以通过对相应消息的属性进行访问
var buf = message.SomeMessage.encode({
list: [
messages.SomeMessage.NESTED_ENUM.VALUE
]
})有关详细信息,请参阅 Google Protocol Buffers 文档 可用类型等
从 v4 版本开始,您现在可以将您的模式编译为一个 JavaScript 文件,然后从 Node 中加载。这意味着您不需要在运行时解析模式,这对于在浏览器或嵌入式设备上使用时非常有用。此外,它还使依赖项占用空间大大减小。
暂无开放 Issues,或尚未同步最近议题。