# proto生成:
npm install protobufjs -g
pbjs -t static-module -w commonjs -o wfcmessage.js wfcmessage.proto
相关文章 https://github.com/fengxianqi/front_end-demos
npm install -g pbjs
## 1.环境安装
npm install protobufjs -g 注意:npm无法安装,使用cnpm
## 2.把wfcmessage.proto转成 wfcmessage.js
pbjs -t static-module -w commonjs -o wfcmessage.js wfcmessage.proto
## 3.把所有proto生成一个js的文件
pbjs -t static-module -w commonjs -o bundle.js *.proto
## 4.把proto生成json
pbjs -t json LkMessageHead.proto xx.proto > bundle.json
## 5.把所选proto生成js (目前使用的方式)
pbjs -t json-module -w commonjs -o bundle.js xx.proto xx.proto
注意:3和5是一样的
import protoRoot from './bundle.js' 上面3或者5生成js文件
import protobuf from 'protobufjs'
// 加密
const PBMessageRequest = protoRoot.lookup('proto包名.proto.类名')
const data = {
content: agentData,
businessBody: 'dsdd',
redPacketState: 18
}
const reqdata = PBMessageRequest.encode(data).finish()
// 解密
const PBMessage = protoRoot.lookup('proto包名.proto.类名')
const buf = protobuf.util.newBuffer(event.data) //event.data需要解密的数据
const decodedResponse = PBMessage.decode(buf)
console.log(decodedResponse,'d')
import protoRoot from '@/protoBuffer/bundle.js'
export const pullMessageHead = (obj, protoName = 'im.proto.xxx') => {
const PBMessageRequest = protoRoot.lookup(protoName)
const encodeData = PBMessageRequest.encode(obj).finish()
return encodeData
}
export const getMessageHead = (obj, protoName = 'im.proto.xxx') => {
const PBMessageResponse = protoRoot.lookup(protoName)
const buff = protobuf.util.newBuffer(obj)
const decodedResponse = PBMessageResponse.decode(buff)
return decodedResponse
}
export function arrayBufferToArray(arrayBuffer) {
return Array.prototype.slice.call(new Uint8Array(arrayBuffer))
}
export function arrayToArrayBuffer(array) {
return new Uint8Array(array).buffer
}
export function strToJson(str = '') {
if (typeof str !== 'string') {
return
}
let obj = JSON.parse(str)
return Object.values(obj)
}
export function getBusinessBody(str) {
if (!str) {
return ''
}
let arr = strToJson(str)
try {
return arrayToArrayBuffer(arr)
} catch (e) {
throw e
}
}