具有请求承诺管道结果的请求(大数据)

时间:2018-02-03 12:08:41

标签: javascript arrays fs request-promise

我尝试从外部API下载一些数据。我想管道每个请求的响应。包含请求URL的数组如下所示:

[ 'https://scihub.copernicus.eu/dhus/odata/v1/Products(\'d98b8730-846f-46d0-a816-5ae4db9f56a7\')/$value',
'https://scihub.copernicus.eu/dhus/odata/v1/Products(\'6edaeb16-3077-45d1-b3f0-fa2d5549f64a\')/$value',
'https://scihub.copernicus.eu/dhus/odata/v1/Products(\'333db2aa-c695-4753-8bd1-e64308af26e1\')/$value',
'https://scihub.copernicus.eu/dhus/odata/v1/Products(\'052cf771-6c4e-4a3a-bc15-51c95a3f37c4\')/$value' ]

我读到request-promise不支持管道请求响应,但我没有找到替代方案,这就是为什么我尝试获取结果的函数如下所示:

var fs = require('fs');
var rp = require('request-promise');

function downloadSentinel(promObj){
return new Promise((resolve,reject) => {
    try {
       var promises = promObj.requestURLS.map(url => rp(url,{auth:auth}).then(body => body.pipe(fs.createWriteStream('./test.zip'))
            .on('finish', () => {
                resolve(promObj);
            })), {concurrency:2});
        Promise.all(promises).then(results => {
            console.log(results)
        });
    } catch (error) {
        reject(error);
    }

})
}

此外,只能同时下载两个产品,我尝试使用Blubird参数concurrency来实现它,但它似乎无法正常工作。

我怎么能解决我的问题?

更新

如果我尝试使用此代码:

var promises = promObj.requestURLS.map(url => rp(url,{auth:auth}).then(
            data => new Promise((resolve,reject) => {
            data.pipe(fs.createWriteStream('./data/' +  promObj.Name[0] + ".zip"))
            .on('finish', () => {
                console.log('Finally finished');
                resolve(promObj);
            })
                .on('error', () => {
                    reject(promObj);
                })})),{concurrency:2});
        Promise.all(promises).then(results => {
            console.log(results)
        });

我收到错误UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): ReferenceError: data.pipe is not a function

我错过了什么?

此外,我认识到我的数据大800MB。它是否太大而无法正确管道?

我现在收到此错误: 在buffer.js:556 if (encoding === undefined) return buf.utf8Slice(start, end); Error: "toString()" failed

0 个答案:

没有答案