[英]How to Pipe Response to a File in Co-Request module & NodeJs?
I am using Co-Request to read Zip file from http url, and i have below code to read from server.. 我正在使用Co-Request从http url读取Zip文件,我有以下代码从服务器读取..
The code works already. 代码已经有效了。 But I dont know how to write the response Zip to a file.
但我不知道如何将响应Zip写入文件。
var co = require( "co" );
var request = require( "co-request" );
var options = {
url: "http://www.example.com/sample.zip",
headers: {
'Token': Appconfig.Affiliate_Token,
'Affiliate-Id' : Appconfig.Affiliate_Id
}
}
console.log( "Downloading : zip file" );
var j = yield request( options );
Co-Request is actually wrapper for Request and I have found below code to pipe file to stream. Co-Request实际上是Request的包装器,我发现下面的代码要管道传输文件。 But not sure how to write the same using Co-Request with yield.
但不确定如何使用带有yield的Co-Request来编写相同的内容。
request.get('http://example.com/img.png').pipe(request.put('http://example.com/img.png'))
Please help how to write response zip to a file using yield and co-request 请帮助如何使用yield和co-request将响应zip写入文件
I think request cant pipe after data has been emitted from the response 我认为请求从响应中发出数据后才能管道化
use request instead of co-request, write a promise to achieve this 使用请求而不是共同请求,写一个承诺来实现这一点
var co = require('co');
var request = require('request');
var fs = require('fs');
var url = 'http://google.com/doodle.png';
var requestPipToFile = function(url, filepath) {
return new Promise(function(resolve, reject) {
try {
var stream = fs.createWriteStream(filepath);
stream.on('finish', function() {
console.log("pipe finish");
return resolve(true);
});
return request(url).pipe(stream);
} catch (e) {
return reject(e);
}
});
};
co(function*() {
var value = (yield requestPipToFile(url, './outfile'));
return value;
}).then(function(value) {
return console.log(value);
}).catch(function(err) {
return console.error(err);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.