安装依赖
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()
执行结果