npm安装与ProtoBuf.js库在cocos creator中的使用
适用于 protobufjs 6.x
安装 protobufjs
>cd E:\project\CCtest
>npm install protobufjs
安装 pbjs
>cd CCtest\node_modules\.bin
>pbjs
等待安装完成。
转换 proto 为 js
// awesome.proto
package awesomepackage;
syntax = "proto3";
message AwesomeMessage {
string awesome_field = 1; // becomes awesomeField
}
转换
>pbjs -t static-module -o awesome.js awesome.proto
拖动 awesome.js 到 cocos creator 的 Script目录
使用
let awesomeRoot = require("awesome");
var AwesomeMessage = awesomeRoot.awesomepackage.AwesomeMessage;
// Exemplary payload
var payload = { awesomeField: "AwesomeString" };
// Verify the payload if necessary (i.e. when possibly incomplete or invalid)
var errMsg = AwesomeMessage.verify(payload);
if (errMsg)
throw Error(errMsg);
// Create a new message
var message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary
// Encode a message to an Uint8Array (browser) or Buffer (node)
var buffer = AwesomeMessage.encode(message).finish();
// ... do something with buffer
// Decode an Uint8Array (browser) or Buffer (node) to a message
var message = AwesomeMessage.decode(buffer);
// ... do something with message
console.log(message);