Javascript NodeJS 使用protobufjs Demo和封装成工具类使用
安装依赖
npm install protobufjs
创建proto文件
syntax = "proto3";
package protobuf;
message Chat{
string msg=1;
}
创建工具类
const protobuf = require("protobufjs");
/**
* 加载类型
* @param filePath
* @param packageName
* @param typeName
* @returns {Promise<any>}
*/
const loadType = async function (filePath,packageName,typeName){
return new Promise(((resolve, reject) => {
protobuf.load(filePath, function(err, root) {
if (err)
{
reject(err);
return
}
// Obtain a message type
var type = root.lookupType(packageName+"."+typeName);
resolve(type)
});
}))
}
const encode = function(type,obj){
let message = type.create(obj)
return type.encode(message).finish()
}
const decode = function(type,buffer){
return type.decode(buffer)
}
module.exports = {
loadType:loadType,
encode:encode,
decode:decode
}
// 使用步骤
/**
* 安装依赖
* npm install protobufjs
*/
/**
* 示范proto文件 protobuf.proto
*
* syntax = "proto3";
package protobuf;
message Chat{
string msg=1;
}
*/
/**
* 使用示范 demo.js
* const util = require('./ProtobufJSUtil')
async function main(){
let type = await util.loadType('./protobuf.proto','protobuf','Chat')
let msg = {msg:'你好呀,我是一条消息'}
let serializedBuffer = util.encode(type,msg)
console.log('压缩后的',serializedBuffer)
let deserializeText = util.decode(type,serializedBuffer)
console.log('解压缩后的',deserializeText)
}
main()
*/
创建测试类测试
const util = require('./ProtobufJSUtil')
async function main(){
let type = await util.loadType('./protobuf.proto','protobuf','Chat')
let msg = {msg:'你好呀,我是一条消息'}
let serializedBuffer = util.encode(type,msg)
console.log('压缩后的',serializedBuffer)
let deserializeText = util.decode(type,serializedBuffer)
console.log('解压缩后的',deserializeText)
}
main()
执行结果
本文来自博客园,作者:HumorChen99,转载请注明原文链接:https://www.cnblogs.com/HumorChen/p/18039558
标签:
protobuf
, javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~