我正在尝试使用axios流式处理传入的响应。响应是一个带有许多键的大型JSON对象,但我只想要一个特定的键。但是此特定键中的值是一个具有数十兆字节数据的数组。有效负载如下所示:
{
"requestTime": "20190606",
"fuelStations": [{
"a": "begin",
...
}, {
"a": "massive",
...
}, {
"a": "array",
...
}, {
"a": "here",
...
}],
"some-other-key": "goes here",
...
}
这是我用于axios的功能。但是我不确定如何在响应中从流中获取fuelStations
数组。
axios.get(baseUrl, { responseType: "stream" }).then(response => {
const stream = response.data;
stream.on("data", chunk => {
// ???
// do something with just the fuelStations key, discard everything else
};
stream.on("end", () => console.log("all done streaming"));
});
答案 0 :(得分:0)
我最终使用了stream-json
软件包。代码看起来像这样:
const stream = await axios
.get(baseUrl, { responseType: "stream" })
.then(response => response.data);
const pipeline = stream
.pipe(Pick.withParser({ filter: "fuel_stations" }))
.pipe(streamArray());
pipeline.on("data", ({ value }) => console.log(value));
pipeline.on("end", () => console.log("end"));