Javascript 如何通过highland从远程JSON数组创建对象流?
从url获取JSONJavascript 如何通过highland从远程JSON数组创建对象流?,javascript,arrays,typescript,stream,highland.js,Javascript,Arrays,Typescript,Stream,Highland.js,从url获取JSONhttp://foo.bar/overview通过: const request = request.get('http://foo.bar/overview'); 在包含对象数组的JSON响应中生成: [ { id: 1, narf: 'foo', poit: 'bar', }, { id: 2, narf: 'fizz', poit: 'buzz',
http://foo.bar/overview
通过:
const request = request.get('http://foo.bar/overview');
在包含对象数组的JSON响应中生成:
[
{
id: 1,
narf: 'foo',
poit: 'bar',
},
{
id: 2,
narf: 'fizz',
poit: 'buzz',
},
]
我现在正在尝试设置一个包含阵列中每个对象的高地流。然而,我似乎只能从请求的整个响应中构建它,而这似乎首先会对整个流方法产生反作用
我的第一个天真解决方案是通过以下方式构建:
let body: [];
request.on('data', (chunk: any) => {
body.push(chunk);
}).on('end', () => {
const responseData = JSON.parse(Buffer.concat(body).toString());
_(responseData) // now I have the stream
});
我还发现highland支持从请求对象本身设置流:
_(request).map((bufferedResponse: Buffer) => {
const overview = <Overview[]> JSON.parse(bufferedResponse.toString()); // again this is the entire respone already
return _(overview); // now I have the stream
});
\(请求).map((bufferedResponse:Buffer)=>{
const overview=JSON.parse(bufferedResponse.toString());//同样,这已经是整个响应了
return uz(overview);//现在我有了流
});
如何在不使用存储在内存中的整个响应的情况下动态地从远程JSON创建对象数组流?我正在尝试,可以通过以下方式使用它构建highland流:
import * as _ from 'highland';
import oboe = require('oboe');
const idStream = _((push: any, next: any) => {
oboe({
url: 'http://foo.bar/overview',
method: 'GET',
headers: {
'X-Token': token,
},
}).node('{id narf poit}', (overview) => {
push(null, overview.id);
return oboe.drop;
}).done((response) => {
// without drop, the entire response would now be stored here
push(null, _.nil);
}).fail((reason) => {
console.error(reason);
push(null, _.nil);
});
});
idStream.each((id: number) => {
console.log(id);
});
印刷品:
1
2