我正在尝试使用 https://github.com/dcodeIO/ProtoBuf.js解析 triments gtfs 数据。
这是我目前的代码,它正确解析 .proto 文件并创建构建器并具有所有预期的属性和方法,当我尝试使用它解码任何数据时它会抛出错误。
Error: Data must be corrupt: Buffer overrun
原型(prototype)文件来自https://developers.google.com/transit/gtfs-realtime/gtfs-realtime-proto
var ProtoBuf = require('protobufjs')
, request = require('request')
var transit = ProtoBuf.protoFromFile('gtfs-realtime.proto').build('transit_realtime')
request('http://developer.trimet.org/ws/V1/FeedSpecAlerts/?appID=618F30BB3062F39AF24AED9EC', parse)
function parse(err, res, body) {
try {
console.log(transit.FeedMessage.decode(res.body))
} catch(e) {
console.log(e)
}
}
感谢 Brian Ferris,我能够解析 header 的第一部分 gtfs_realtime_version: "1"
但解析器在下一个组件(时间戳 uint64)上失败
感谢
最佳答案
在搜索您遇到的相同问题时,我一直在寻找您的问题,希望我能帮助其他人。在网上搜索了比我应该拥有的时间长得多的时间之后,我想出了一些可行的方法。在我解码了一个有效的提要之前,我不太了解这些数据。
这在很大程度上似乎与数据的读取方式有关。我不是 NodeJS 的人所以我不知道为什么,但这取决于如何使用 http
而不是 request
读取数据进行解码。我无法使用相同的方法来处理数据的 request
。
部分内容我从 https://github.com/dcodeIO/ProtoBuf.js/wiki/How-to-read-binary-data-in-the-browser-or-under-node.js%3F 中找到但我还不太了解如何使用 protobufjs
,所以我在这里为其他人提供了一个工作示例。希望对您有所帮助。
var ProtoBuf = require('protobufjs');
var http = require("http");
// create a protobuf decoder
var transit = ProtoBuf.protoFromFile('gtfs-realtime.proto').build('transit_realtime');
// your protobuf binary feed URL
var feedUrl = "...";
// HTTP GET the binary feed
http.get(feedUrl, parse);
// process the feed
function parse(res) {
// gather the data chunks into a list
var data = [];
res.on("data", function(chunk) {
data.push(chunk);
});
res.on("end", function() {
// merge the data to one buffer, since it's in a list
data = Buffer.concat(data);
// create a FeedMessage object by decooding the data with the protobuf object
var msg = transit.FeedMessage.decode(data);
// do whatever with the object
console.log(msg);
});
});
关于javascript - 你如何在 Node 中解码 gtfs protobufs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18523235/