1

通过以下方式从 url 获取 JSON 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
});

如何在不使用存储在内存中的整个响应的情况下即时从远程 JSON 创建一个对象数组流?

4

1 回答 1

1

我正在尝试oboejs,可以通过以下方式构建高地溪流:

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
于 2016-12-13T19:54:34.480 回答