首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用.proto文件在node.js中解码编码的协议缓冲区数据

如何用.proto文件在node.js中解码编码的协议缓冲区数据
EN

Stack Overflow用户
提问于 2020-09-28 06:44:38
回答 1查看 4.9K关注 0票数 4

我对协议缓冲区很陌生,我试图从api响应中解码数据。

我从api响应中获得编码的数据,我有一个.proto文件来解码数据,如何在nodeJS中解码数据。我尝试过使用protobuf.js,但我很困惑,我花了几个小时试图解决我的问题,寻找资源,但我无法找到解决方案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-28 07:38:45

Protobufj允许我们基于.proto文件对来自二进制数据的原始消息进行编码和解码。

下面是一个简单的编码示例,然后使用该模块解码测试消息:

代码语言:javascript
复制
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文件:

代码语言:javascript
复制
package testpackage;
syntax = "proto3";

message testMessage {
    uint32 timestamp = 1;
    string message = 2;
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64097146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档