You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中使用Axios解码Protobuf格式GTFS实时数据报错求助

解决Axios下载Protobuf格式GTFS实时数据时的"illegal buffer"错误

问题原因

你遇到的"illegal buffer"错误,根源是Axios默认会把响应数据解析为字符串,而gtfs-realtime-bindings的decode方法需要的是二进制缓冲区(Buffer/ArrayBuffer/Uint8Array),字符串无法被protobuf正确解析,因此抛出错误。

解决方案

修改Axios请求配置,指定responseType: 'arraybuffer'获取二进制数据,再根据运行环境转换为protobuf可识别的格式:

import axios from "axios";
import * as GtfsRealtimeBindings from "gtfs-realtime-bindings";

const url = "https://www.rtd-denver.com/files/gtfs-rt/TripUpdate.pb";
export type RealtimeGtfsUrl = string;

export async function decodeRealtimeGtfs(
  url: RealtimeGtfsUrl,
): Promise<GtfsRealtimeBindings.transit_realtime.FeedMessage> {
  // 配置Axios获取二进制响应数据
  const response = await axios.get(url, { responseType: 'arraybuffer' });
  // Node.js环境下将ArrayBuffer转为Buffer,浏览器环境替换为new Uint8Array(response.data)
  const binaryData = Buffer.from(response.data);
  return GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(binaryData);
}

// 调用函数并处理结果
decodeRealtimeGtfs(url)
  .then(result => console.log(result))
  .catch(err => console.error(err));

关键说明

  • responseType: 'arraybuffer':强制Axios保留原始二进制响应,不自动解析为字符串。
  • 格式转换:Node.js用Buffer.from()转换ArrayBuffer,浏览器环境直接使用Uint8Array即可,两者都能被protobuf的decode方法识别。
  • 简化异步写法:将原代码中await + .then()的混合写法改为纯async/await风格,更符合TypeScript异步编程习惯。

内容的提问来源于stack exchange,提问作者Connor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:05:01