如何在node.js服务器流式http请求中处理JSON流响应数组

Posted

技术标签:

【中文标题】如何在node.js服务器流式http请求中处理JSON流响应数组【英文标题】:How to process Array of JSON Stream Response in node.js server streaming http resquest 【发布时间】:2021-10-12 18:39:22 【问题描述】:

流响应的形式为

[
  "id":0,
  "name":name0

,

  "id":1,
  "name":name1

]

如果我使用node-fetch流特征来获取,迭代response.body,块数据被随机切割对象。我无法解析它。我猜node-fetch不支持json数组,无法识别[]

如何处理json的流式数组?或任何其他 3rd 方库? 示例代码:

const fetch = require('node-fetch');

async function main() 
  const response = await fetch(url);
  try 
    for await (const chunk of response.body) 
      console.log('----start')
      console.dir(JSON.parse(chunk.toString()));
      console.log('----end')
   catch (err) 
    console.error(err.stack);
  


main()

【问题讨论】:

【参考方案1】:

流解析外部 JSON 源的一种方法是将 node-fetchstream-json 结合起来解析传入的数据,而不管(字符串)数据如何分块。

import util from "util";
import stream from "stream";
import StreamArray from "stream-json/streamers/StreamArray.js";
import fetch from "node-fetch";

const response = await fetch(url);

await util.promisify(stream.pipeline)(
  response.body,
  StreamArray.withParser(),
  async function( parsedArrayEntriesIterable )
    for await (const key: arrIndex, value: arrElem of parsedArrayEntriesIterable) 
      console.log("Parsed array element:", arrElem);
    
  
)

stream.pipeline()async function 需要 NodeJS >= v13.10

【讨论】:

以上是关于如何在node.js服务器流式http请求中处理JSON流响应数组的主要内容,如果未能解决你的问题,请参考以下文章