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



流响应是

的形式
[{
"id":0,
"name":name0
}
,
{
"id":1,
"name":name1
}
]

如果我使用node-fetch流特性来获取,迭代响应。体中,块数据是随机切割的对象。我无法解析它。我猜node-fetch不支持json数组,不能识别[,]

如何处理json的流数组?或者其他第三方库?示例代码:

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()

对外部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()withasync functionrequire NodeJS>= v13.10

最新更新