讲师中心 微信公众号

工具推荐

视频效率加速
Seko
Seko

AI短剧一键生成成片

updream

一键生成高质量推广成片

AniShort
AniShort

AI短剧协同制作平台

立刻MV
立刻MV

低成本歌曲 MV、视频生成

JavaScript Fetch API 怎么处理接口返回的 Avro 数据

星辰大大_7055

星辰大大_7055

发布时间:2026-11-15 12:54:19

|

872人浏览过

|

来源于php中文网

原创

使用 fetch api 处理 avro 数据的核心在于将二进制流转换为 javascript 可操作的 buffer,再结合 avro schema 进行反序列化。具体做法是调用 response.arraybuffer() 获取原始字节,随后利用 avsc 库的 parse() 和 read() 方法解析数据。若未提供 schema,需先通过 avro 标准格式(magic bytes)提取内嵌 schema 或依赖外部约定。

JavaScript Fetch API 怎么处理接口返回的 Avro 数据

如何从 Response 中提取二进制数据并验证完整性

直接回答:通过 response.arrayBuffer() 获取二进制数据后,检查前 5 个字节是否为 Avro Magic Bytes(0x41, 0x56, 0x72, 0x4F, 0x2E),以确认数据格式正确且未被截断。这一步确保后续解析不会因数据损坏而失败。

JavaScript Fetch API 怎么处理接口返回的 Avro 数据

const response = await fetch('https://api.example.com/data.avro');
if (!response.ok) throw new Error('Network error');

const buffer = await response.arrayBuffer();
const view = new DataView(buffer);

// Check Magic Bytes: 'AvRO' + version byte (0x01)
const magicBytes = String.fromCharCode(
  view.getUint8(0),
  view.getUint8(1),
  view.getUint8(2),
  view.getUint8(3)
);

if (magicBytes !== 'AvRO') {
  throw new Error('Invalid Avro file: missing magic bytes');
}

if (view.getUint8(4) !== 0x01) {
  throw new Error('Unsupported Avro version');
}

console.log('Binary data extracted and validated successfully.');

如何解析包含内嵌 Schema 的 Avro 数据

直接回答:Avro 文件头部包含元数据块,其中存储了 JSON 格式的 Schema。通过读取偏移量处的元数据,提取 Schema 字符串,使用 avsc.parse() 创建类型对象,再用 type.read(buffer) 完成反序列化。此过程自动处理长度前缀和编码细节。

JavaScript 测试模式
JavaScript 测试模式

使用 Jest、Vitest 和 Testing Library 实施全面的测试策略,包括单元测试、集成测试和端到端测试,涵盖模拟、测试夹具和测试驱动开发。在编

下载

立即学习“Java免费学习笔记(深入)”;

JavaScript Fetch API 怎么处理接口返回的 Avro 数据

const avro = require('avsc');

async function parseAvroWithEmbeddedSchema(buffer) {
  const view = new DataView(buffer);
  
  // Skip Magic Bytes (5 bytes)
  // Next is sync marker (16 bytes)
  // Then metadata block length (int, 4 bytes)
  const metaLengthOffset = 5 + 16;
  const metaLength = view.getInt32(metaLengthOffset, false); // big-endian
  
  // Read metadata block
  const metaStart = metaLengthOffset + 4;
  const metaEnd = metaStart + metaLength;
  
  // Metadata is encoded as a string in Avro format
  // For simplicity, assume UTF-8 and skip complex Avro encoding decoding here
  // In production, use a library like 'avro-js' or 'avsc' to decode the metadata block properly
  // Here we simulate extracting the schema string from the metadata
  
  // Note: Real implementation requires decoding Avro's binary string encoding
  // For this example, we assume we have the schema string available
  const schemaString = extractSchemaFromMetadata(buffer, metaStart, metaLength);
  
  const schema = avro.parse(schemaString);
  const records = [];
  let offset = metaEnd + 16; // Skip sync marker after metadata
  
  while (offset < buffer.byteLength) {
    // Each record is preceded by a count (long, 8 bytes)
    // If count is 0, end of file
    const countView = new DataView(buffer, offset, 8);
    const count = Number(countView.getBigInt64(0, false));
    
    if (count === 0) break;
    
    offset += 8;
    
    for (let i = 0; i < count; i++) {
      const record = schema.read(buffer, offset);
      records.push(record);
      // Update offset based on record size - simplified
      // In reality, you need to know the exact size or use schema.read which returns next offset
      // avsc's read method can be tricky with offsets, so often people use stream or custom loop
      // For this example, we assume a simple sequential read
      // A more robust way is to use schema.read(buffer, offset) and get the new offset
      // But avsc doesn't return new offset directly in read() for all versions
      // Let's use a simpler approach: parse the whole buffer if it's a single object
      // Or use avro.createFileReader for streaming
      
      // For this specific example, let's assume we just read one record for simplicity
      // and update offset manually based on a known size or use a parser that handles it
      // To keep it accurate, let's use avro's built-in file reader if possible
      // But since we have a buffer, let's stick to manual parsing logic
      
      // Actually, avsc's `read` method takes a buffer and an offset, and returns the value.
      // It does NOT update the offset. You need to calculate the size yourself or use a different method.
      // This is a common pitfall. Let's correct this:
      // Use `avro.Type.forSchema(schema).read(buffer, offset)` but you still need to know the size.
      // A better way for multiple records is to use `avro.createFileReader` on a stream/buffer.
      
      // Let's rewrite the loop to use a proper method for reading multiple records
      // We'll use a helper to get the size of the encoded record
      const recordSize = getRecordSize(schema, record); // Placeholder
      offset += recordSize;
    }
  }
  
  return records;
}

// Helper to extract schema from metadata (simplified)
function extractSchemaFromMetadata(buffer, start, length) {
  // This is a placeholder. Real implementation needs to decode Avro's binary string encoding.
  // Avro strings are encoded as: [length] [bytes]
  // The metadata block contains key-value pairs where keys are "schema"
  // We need to find the "schema" key and decode its value.
  // For brevity, we assume the schema is at a known position or use a library.
  // In practice, use `avro` library's ability to parse the file header.
  return '{"type":"record","name":"Test","fields":[{"name":"f1","type":"string"}]}';
}

function getRecordSize(schema, record) {
  // Calculate size of encoded record
  // This is complex and depends on the schema
  // For this example, we assume a fixed size or use a different approach
  // A more accurate way is to use `avro.Type.forSchema(schema).write(record, buffer, offset)` 
  // to write and then check the difference, but we are reading.
  // Let's use a simpler approach: use `avro.createFileReader` for the whole buffer
  return 0; // Placeholder
}

// Better approach using avro's file reader for buffers
async function parseAvroProperly(buffer) {
  const avro = require('avsc');
  const fs = require('fs');
  const { Readable } = require('stream');
  
  // Create a readable stream from the buffer
  const stream = Readable.from(buffer);
  
  // Create a file reader
  const reader = await avro.createFileReader(stream);
  
  const schema = reader.schema();
  console.log('Schema:', schema);
  
  const records = [];
  for await (const record of reader) {
    records.push(record);
  }
  
  return records;
}

如何处理没有内嵌 Schema 的 Avro 数据

直接回答:当 Avro 数据不包含内嵌 Schema 时,必须预先知道或使用外部提供的 Schema JSON 字符串。直接使用 avsc.parse() 解析该 Schema,然后对每个记录使用 type.read() 进行反序列化。这种方式要求客户端和服务端严格同步 Schema 版本,否则会导致解析错误。

热门AI工具

更多
豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

Seko
Seko Hot

一款AI视频创作工具,主要用于商汤科技推出的创编一体的AI短视频创作Agent,适合需要提升相关任务效率的用户。

讯飞智文

一款面向学习和办公场景的AI文档创作工具,可辅助生成PPT与Word文档,提高资料整理和内容制作效率。

VibeKnow
VibeKnow Hot

一款AI视频创作工具,主要用于全球首个AI知识视频创作平台,文档、文章、网页,一键生成视频,适合需要提升相关任务效率的用户。

UP简历
UP简历 Hot

一款AI办公效率工具,主要用于基于AI技术的免费在线简历制作工具,适合需要提升相关任务效率的用户。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

Loomy
Loomy Hot

一款AI工具,主要用于科大讯飞发布的桌面级 AI 助理,比 OpenClaw 更易用、更安全!,适合需要提升相关任务效率的用户。

超级麦吉

一款通过数字员工协作完成调研、数据分析与文档制作的AI办公平台。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

相关专题

更多
js获取数组长度的方法
js获取数组长度的方法

在js中,可以利用array对象的length属性来获取数组长度,该属性可设置或返回数组中元素的数目,只需要使用“array.length”语句即可返回表示数组对象的元素个数的数值,也就是长度值。php中文网还提供JavaScript数组的相关下载、相关课程等内容,供大家免费下载使用。

5926

2023.06.20

js刷新当前页面
js刷新当前页面

js刷新当前页面的方法:1、reload方法,该方法强迫浏览器刷新当前页面,语法为“location.reload([bForceGet]) ”;2、replace方法,该方法通过指定URL替换当前缓存在历史里(客户端)的项目,因此当使用replace方法之后,不能通过“前进”和“后退”来访问已经被替换的URL,语法为“location.replace(URL) ”。php中文网为大家带来了js刷新当前页面的相关知识、以及相关文章等内容

1429

2023.07.04

js四舍五入
js四舍五入

js四舍五入的方法:1、tofixed方法,可把 Number 四舍五入为指定小数位数的数字;2、round() 方法,可把一个数字舍入为最接近的整数。php中文网为大家带来了js四舍五入的相关知识、以及相关文章等内容

5844

2023.07.04

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

1060

2023.09.01

JavaScript转义字符
JavaScript转义字符

JavaScript中的转义字符是反斜杠和引号,可以在字符串中表示特殊字符或改变字符的含义。本专题为大家提供转义字符相关的文章、下载、课程内容,供大家免费下载体验。

2036

2023.09.04

js生成随机数的方法
js生成随机数的方法

js生成随机数的方法有:1、使用random函数生成0-1之间的随机数;2、使用random函数和特定范围来生成随机整数;3、使用random函数和round函数生成0-99之间的随机整数;4、使用random函数和其他函数生成更复杂的随机数;5、使用random函数和其他函数生成范围内的随机小数;6、使用random函数和其他函数生成范围内的随机整数或小数。

4025

2023.09.04

如何启用JavaScript
如何启用JavaScript

JavaScript启用方法有内联脚本、内部脚本、外部脚本和异步加载。详细介绍:1、内联脚本是将JavaScript代码直接嵌入到HTML标签中;2、内部脚本是将JavaScript代码放置在HTML文件的`<script>`标签中;3、外部脚本是将JavaScript代码放置在一个独立的文件;4、外部脚本是将JavaScript代码放置在一个独立的文件。

5333

2023.09.12

Js中Symbol类详解
Js中Symbol类详解

javascript中的Symbol数据类型是一种基本数据类型,用于表示独一无二的值。Symbol的特点:1、独一无二,每个Symbol值都是唯一的,不会与其他任何值相等;2、不可变性,Symbol值一旦创建,就不能修改或者重新赋值;3、隐藏性,Symbol值不会被隐式转换为其他类型;4、无法枚举,Symbol值作为对象的属性名时,默认是不可枚举的。

3500

2023.09.20

Go-Zero API开发使用教程
Go-Zero API开发使用教程

本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

40

2026.11.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
WebStorm 官方调试文档
WebStorm 官方调试文档

共0课时 | 0人学习

React 教程
React 教程

共58课时 | 12.5万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 6.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn