I am using Co-Request to read Zip file from http url, and i have below code to read from server..
The code works already. But I dont know how to write the response Zip to a file.
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. But not sure how to write the same using Co-Request with yield.
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
HTTP Module: The HTTP module is the built-in module that can be used without external installing command.
Request and Response object both are the callback function parameters and are used for Express. js and Node. js. You can get the request query, params, body, headers, and cookies. It can overwrite any value or anything there.
A stream is an abstract interface for working with streaming data in Node.js. The node:stream module provides an API for implementing the stream interface. There are many stream objects provided by Node.js. For instance, a request to an HTTP server and process.stdout are both stream instances.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With