我使用protobufjs通过API管理我的数据。它在大多数情况下都工作得很好,但在一条消息的一个实例中,我得到了一个“非法缓冲区”异常。这是由库中的一些内部代码抛出的。我在这里粘贴Chrome调试器的视觉,而停止在一个断点se到抛出语句。Chromer debugger output
正如你所看到的,Chrome告诉我缓冲区确实是一个Uint8Array ( 755字节)。为什么if语句解析为false并导致throw语句执行?"buffer instanceof Uint8Array“和"Array.isArray(buffer)”都为真。
更新
我写了一些代码(必要地从protobufjs复制并简化了它):
function test() {
var data = new Uint8Array([10, 9, 18, 7, 99, 111, 110, 110, 101, 99, 116, 16, 1]);
testProtobuf(data);
}
function Reader(buffer) {
this.buf = buffer;
this.pos = 0;
this.len = buffer.length;
}
var create_array = function (buffer) {
console.log(buffer);
if (buffer instanceof Uint8Array || Array.isArray(buffer))
return new Reader(buffer);
throw Error("illegal buffer");
}
function testProtobuf (data) {
try {
create_array(data);
}
catch (e) { console.log('Exception')};
}当我调用test() (它调用testProtobuf,而后者又调用create_array )时,没有抛出异常。我还在实际代码中从我的onmessage方法调用testProtobuf。在这种情况下,仍会抛出异常。如您所见,我在控制台上记录了缓冲区。两个日志是相同的(我确保测试数据是相同的)。
这是Chrome控制台:Console output in Chrome
发布于 2021-07-05 23:03:40
我找到了这个问题的解决方案here
Sample.deserializeBinary(Array.from(buffer));下面是我的typescript代码中的一个例子:
const arrayBuffer = await res.arrayBuffer();
const array = new Uint8Array(arrayBuffer);
const response: Uint8Array = (Array.from(array) as unknown) as Uint8Array;
rpcImplCallback(null, response);https://stackoverflow.com/questions/63428242
复制相似问题