Node Express解析Protobuf

文章转载自我自己的小破站 摸鱼好地方。欢迎大佬们围观~

Protobuf 简介

Protobuf 提供了一种语言中立、平台中立、可扩展的机制,用于以向前兼容和向后兼容的方式序列化结构化数据。它类似于 JSON,只是它更小更快,并且生成本地语言绑定。

Protobuf 是定义语言(在 .proto文件中创建)、proto 编译器生成的与数据接口的代码、特定于语言的运行时库以及写入文件(或通过网络连接)。

更多介绍可以查看 Google开发文档

Express端

Protobuf 的请求体使用二进制,所以关键在于 Express 接收到数据后,需要将二进制内容进行编解码,转换成对应的JSON结构体

const axios = require('axios');
const express = require('express');
const protobuf = require('protobufjs');

const app = express();

run().catch(err => console.log(err));

async function run() {
  const root = await protobuf.load('user.proto');

  const doc = { name: 'Bill', age: 30 };
  const User = root.lookupType('userpackage.User');

  app.get('/user', function(req, res) {
    res.send(User.encode(doc).finish());
  });

  // 在decode之前需要用raw中间件处理一遍protobuf数据
  app.post('/user', express.raw({ type: '*/*' }), function(req, res) {
    // Assume `req.body` contains the protobuf as a utf8-encoded string
    const user = User.decode(Buffer.from(req.body));
    Object.assign(doc, user);
    res.end();
  });

  await app.listen(3000);
}

Client端

let data = await axios.get('http://localhost:3000/user').then(res => res.data);

// "Before POST User { name: 'Bill', age: 30 }"
console.log('Before POST', User.decode(Buffer.from(data)));
const postBody = User.encode({ name: 'Joe', age: 27 }).finish();
await axios.post('http://localhost:3000/user', postBody).
then(res => res.data);

data = await axios.get('http://localhost:3000/user').then(res => res.data);
// "After POST User { name: 'Joe', age: 27 }"
console.log('After POST', User.decode(Buffer.from(data)));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用Node.js解析protobuf的两个例子: 1. 使用protobuf.js库解析protobuf文件 ```javascript const protobuf = require('protobufjs'); // 加载protobuf文件 protobuf.load('path/to/your/proto/file.proto', function(err, root) { if (err) throw err; // 获取消息类型 const MessageType = root.lookupType('your.package.MessageType'); // 创建一个消息对象 const message = MessageType.create({ /* 消息字段 */ }); // 将二进制数据解码为消息对象 const buffer = Buffer.from('your_protobuf_data', 'base64'); const decodedMessage = MessageType.decode(buffer); // 将消息对象编码为二进制数据 const encodedMessage = MessageType.encode(message).finish(); // 将消息对象转换为JSON格式 const jsonMessage = MessageType.toObject(message, { longs: String, enums: String, bytes: String }); // 打印解析结果 console.log(decodedMessage); console.log(encodedMessage); console.log(jsonMessage); }); ``` 2. 使用google-protobuf解析protobuf文件 ```javascript const protobuf = require('google-protobuf'); // 加载protobuf文件 const root = protobuf.loadSync('path/to/your/proto/file.proto'); // 获取消息类型 const MessageType = root.lookupType('your.package.MessageType'); // 创建一个消息对象 const message = MessageType.create({ /* 消息字段 */ }); // 将二进制数据解码为消息对象 const buffer = Buffer.from('your_protobuf_data', 'base64'); const decodedMessage = MessageType.decode(buffer); // 将消息对象编码为二进制数据 const encodedMessage = MessageType.encode(message).finish(); // 将消息对象转换为JSON格式 const jsonMessage = MessageType.toObject(message, { longs: String, enums: String, bytes: String }); // 打印解析结果 console.log(decodedMessage); console.log(encodedMessage); console.log(jsonMessage); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZTao-z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值