使用$fetch和ArrayBuffer获取Float32向量返回错误结果求助
问题:Nuxt3中$fetch获取Float32Array二进制文件数据异常
现象
用Float32Array生成的二进制文件,Node.js本地读写完全正常,但在Nuxt3中通过$fetch(设置responseType: "arrayBuffer")获取时出现异常:
- 原数据应为60字节,接收后ArrayBuffer长度变为70字节
- 转换后的Float32Array数值混乱,仅截取前10字节后的最后8个数值正确
- 大文件场景下,原数据约1.5MB,接收后变为2.5MB,无法确定有效数据范围
- 怀疑涉及大小端问题,但暂未确认
Node端代码
创建文件
fs.writeFileSync(`${dir_path}/test.f32`, new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]), 'binary');
本地读取验证
const f32test = fs.readFileSync(`${dir_path}/test.f32`); const F32 = new Float32Array(f32test.buffer, f32test.byteOffset, f32test.length / 4); console.log(F32); // 输出:[1,2,3,4,5,6,7,8,9...]
Nuxt3端代码
获取数据
const data = await $fetch('/api/vector', { responseType: "arrayBuffer" }); const f32 = new Float32Array(data, 0, data.byteLength / Float32Array.BYTES_PER_ELEMENT);
截取10字节后的测试代码及结果
new Float32Array(temp1.slice(10), 0, 15);
输出结果:
[3, -1.8671875, 2.3223719449255193e-41, 5.9296793937683105, -1.8671875, 2.3223719449255193e-41, 5.9296793937683105, 8, 9, 10, 11, 12, 13, 14, 15]
内容的提问来源于stack exchange,提问作者user1658162
相关产品推荐
相关产品推荐

