【发布时间】:2018-09-07 23:04:48
【问题描述】:
我正在尝试异步获取某些 pdf 文件的内容。为此,我将Promise.mapSeries 与来自bluebird 的request.getAsync 和spread 一起使用。
但是在then 中,我需要直接使用pipe 和createWriteStream 来获得request 的结果。比如:
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);
})
我的问题:
如何使用pipe 函数将getAsync 的结果管道 到文件中?有可能吗?
PD:我知道我可以使用fs.promises,但只是想知道是否可以按照我发帖的方式进行
【问题讨论】:
-
作为评论 - 在下面的答案和 cmets 之后 - 我只想引用 here 所说的话:“STREAMING THE RESPONSE(例如
.pipe(...)) 是DISCOURAGED,因为 Request-Promise 会不必要地增加大型请求的内存占用。为此请使用原始请求库。您可以在同一个项目中使用这两个库"
标签: javascript node.js asynchronous promise bluebird