使用bluebird的request.getAsync,如何“管道”到文件

问题描述 投票:0回答:1

我试图异步获取某些pdf文件的内容。要做到这一点,我使用Promise.mapSeriesrequest.getAsync和蓝鸟spread

但在then我需要直接使用requestpipe获得createWriteStream的结果。就像是:

request(url).pipe(fs.createWriteStream(file));

这是代码,我正在使用:

const Promise = require('bluebird');
const request = Promise.promisifyAll(require('request'), { multiArgs: true });
const fs = Promise.promisifyAll(require("fs"));

const urls = ['http://localhost/test-pdf/one.pdf', 'http://localhost/test-pdf/two.pdf'];

Promise.mapSeries(urls, url => {
    return request.getAsync({url: url, encoding:'binary'}).spread((response, body) => {
        if (response.statusCode == 200){
            let r = {};
            r.name = url.match(/\/([^/]*)$/)[1]; // get the last part of url (file name)
            r.content = body;
            console.log(`Getting ${r.name}`);
            return r;
        }
        else if (response.statusCode == 404){
            console.log(`The archive ${url.match(/\/([^/]*)$/)[1]} does not exists`);
        }
        else throw new Error(`Unsuccessful attempt. Code: ${response.statusCode}`);
    });
}).then((result) => {
    // Here I want to 'pipe' to a file the result from 'getAsync'
}).catch((error) =>{
    console.error(error);
})

我的问题:

如何使用getAsync函数将pipe的结果传递给文件?有可能的?

PD:我知道我可以使用fs.promises,但只是想知道是否有可能以我发布的方式进行

javascript node.js asynchronous promise bluebird
1个回答
1
投票

我认为答案已经在问题中,.then()似乎是你寻求的.pipe()

可能缺少的是(result)应该是(results),即。由{name, content}引起的所有Promise.mapSeries(urls, ...)对的数组。

Promise.mapSeries(urls, url => {
    return request.getAsync({'url':url, 'encoding':'binary'}).spread((response, body) => {
        if (response.statusCode == 200) {
            return {
                'name': url.match(/\/([^/]*)$/)[1], // get the last part of url (file name)
                'content': body
            };
        } else if (response.statusCode == 404) {
            throw new Error(`The archive ${url.match(/\/([^/]*)$/)[1]} does not exist`);
        } else {
            throw new Error(`Unsuccessful attempt. Code: ${response.statusCode}`);
        }
    });
}).then((results) => {
    // Here write each `result.content` to file.
}).catch((error) => {
    console.error(error);
});

在实践中,您可能不会选择以这种方式编写它,因为在任何写入开始之前,每个getAsync()都需要完成。

在大多数情况下(可能是你想要的那种情况)更好的流量将是每个成功的getAsync()的内容尽快写入:

Promise.mapSeries(urls, url => {
    let name = url.match(/\/([^/]*)$/)[1]; // get the last part of url (file name)
    return request.getAsync({'url':url, 'encoding':'binary'}).spread((response, body) => {
        if (response.statusCode == 200) {
            // write `body.content` to file.
        } else if (response.statusCode == 404) {
            throw new Error(`The archive ${name} does not exist`);
        } else {
            throw new Error(`Unsuccessful attempt. Code: ${response.statusCode}`);
        }
    });
}).catch((error) => {
    console.error(error);
});

更进一步,您可能会选择更好地处理错误,例如您可能希望:

  • 抓住个人网址/获取/写入错误
  • 编译成功/失败统计数据。

这样的事情可能是:

Promise.mapSeries(urls, url => {
    let name = url.match(/\/([^/]*)$/)[1] || ''; // get the last part of url (file name)
    if(!name) {
        throw new RangeError(`Error in input data for ${url}`);
    }
    return request.getAsync({'url':url, 'encoding':'binary'}).spread((response, body) => {
        if (response.statusCode == 200) {
            // write `body.content` to file.
            return { name, 'content': body };
        } else if (response.statusCode == 404) {
            throw new Error(`The archive ${name} does not exist`);
        } else {
            throw new Error(`Unsuccessful attempt. Code: ${response.statusCode}`);
        }
    })
    .catch(error => ({ name, error }));
}).then((results) => {
    let successes = results.filter(res => !res.error).length;
    let failures = results.filter(res => !!res.error).length;
    let total = results.length;
    console.log({ successes, failures, total }); // log success/failure stats
}).catch((error) => {
    console.error(error); // just in case some otherwise uncaught error slips through
});
© www.soinside.com 2019 - 2024. All rights reserved.