// 加载 .bytes 文件的基本方法
resources.load('binaryData', (err, asset) => {
if (err) {
console.error('加载失败:', err);
return;
}
// 获取二进制数据
const arrayBuffer = asset._file;
// 转换为 Uint8Array
const uint8Array = new Uint8Array(arrayBuffer);
// 检查数据是否为空
if (uint8Array.length === 0) {
console.warn('警告: 加载的数据为空');
return;
}
console.log('数据大小:', uint8Array.length, '字节');
// 根据文件类型进行反序列化
if (isProtobufData(uint8Array)) {
// Protobuf 反序列化
const message = MyMessage.decode(uint8Array);
console.log('Protobuf 数据:', message);
} else if (isJsonData(uint8Array)) {
// JSON 反序列化
const text = new TextDecoder().decode(uint8Array);
const jsonData = JSON.parse(text);
console.log('JSON 数据:', jsonData);
} else {
// 原始二进制数据
console.log('原始二进制数据:', uint8Array);
}
});
// 辅助函数:检测是否是Protobuf数据
isProtobufData(uint8Array) {
if (uint8Array.length < 8) return false;
const header = new Uint8Array(uint8Array.buffer, 0, 8);
const decoder = new TextDecoder();
const headerStr = decoder.decode(header);
return headerStr === "PROTOBUF";
}
// 辅助函数:检测是否是JSON数据
isJsonData(uint8Array) {
try {
const decoder = new TextDecoder();
const text = decoder.decode(uint8Array);
JSON.parse(text);
return true;
} catch (e) {
return false;
}
}