我对协议缓冲区很陌生,我试图从api响应中解码数据。
我从api响应中获得编码的数据,我有一个.proto文件来解码数据,如何在nodeJS中解码数据。我尝试过使用protobuf.js,但我很困惑,我花了几个小时试图解决我的问题,寻找资源,但我无法找到解决方案。
发布于 2020-09-28 07:38:45
Protobufj允许我们基于.proto文件对来自二进制数据的原始消息进行编码和解码。
下面是一个简单的编码示例,然后使用该模块解码测试消息:
const protobuf = require("protobufjs");
async function encodeTestMessage(payload) {
const root = await protobuf.load("test.proto");
const testMessage = root.lookupType("testpackage.testMessage");
const message = testMessage.create(payload);
return testMessage.encode(message).finish();
}
async function decodeTestMessage(buffer) {
const root = await protobuf.load("test.proto");
const testMessage = root.lookupType("testpackage.testMessage");
const err = testMessage.verify(buffer);
if (err) {
throw err;
}
const message = testMessage.decode(buffer);
return testMessage.toObject(message);
}
async function testProtobuf() {
const payload = { timestamp: Math.round(new Date().getTime() / 1000), message: "A rose by any other name would smell as sweet" };
console.log("Test message:", payload);
const buffer = await encodeTestMessage(payload);
console.log(`Encoded message (${buffer.length} bytes): `, buffer.toString("hex"));
const decodedMessage = await decodeTestMessage(buffer);
console.log("Decoded test message:", decodedMessage);
}
testProtobuf();和.proto文件:
package testpackage;
syntax = "proto3";
message testMessage {
uint32 timestamp = 1;
string message = 2;
}https://stackoverflow.com/questions/64097146
复制相似问题