代码之家  ›  专栏  ›  技术社区  ›  robe007 Leo Aguirre

使用请求.getAsync从蓝鸟,如何'管道'到一个文件

  •  0
  • robe007 Leo Aguirre  · 技术社区  · 8 年前

    Promise.mapSeries 具有 request.getAsync spread 青鸟 .

    但是在 then 我要知道结果 request pipe 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 功能?有可能吗?

    警察局: 我知道我可以用 fs.promises ,但我只是想知道是否有可能以我发布的方式来做

    1 回复  |  直到 8 年前
        1
  •  1
  •   Roamer-1888    8 年前

    我想答案已经在这个问题上了 .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);
    });
    

    • 捕获单个url/获取/写入错误
    • 编译成功/失败统计。

    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
    });
    
    推荐文章