首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用axios流式传输响应,但只需要特定的键

使用axios流式传输响应,但只需要特定的键
EN

Stack Overflow用户
提问于 2019-06-14 14:17:35
回答 1查看 1.4K关注 0票数 0

我正在尝试使用axios流式传输传入的响应。响应是一个具有多个键的大型JSON对象,但我只需要一个特定的键。但是这个特定键中的值是一个具有数十兆字节数据的数组。有效负载如下所示:

代码语言:javascript
运行
复制
{
  "requestTime": "20190606",
  "fuelStations": [{
    "a": "begin",
    ...
  }, {
    "a": "massive",
    ...
  }, {
    "a": "array",
    ...
  }, {
    "a": "here",
    ...
  }],
  "some-other-key": "goes here",
  ...
}

这就是我使用的axios。但我不确定如何在流传输时从响应中获取fuelStations数组。

代码语言:javascript
运行
复制
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"));
});
EN

回答 1

Stack Overflow用户

发布于 2019-06-15 14:26:11

我最终使用了stream-json包。代码看起来像这样:

代码语言:javascript
运行
复制
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"));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56592444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档