Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getFile and getStream mirror putFile and putStream #123

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 54 additions & 2 deletions lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ Client.prototype.get = function(filename, headers){
* @api public
*/

Client.prototype.getFile = function(filename, headers, fn){
Client.prototype.getStream = function(filename, headers, fn){
if ('function' == typeof headers) {
fn = headers;
headers = {};
Expand All @@ -383,6 +383,58 @@ Client.prototype.getFile = function(filename, headers, fn){
return req;
};

/**
* GET `filename` and write to `dest` with optional `headers` and callback `fn`
* with a possible exception
*
* @param {String} filename
* @param {Object|Function} headers
* @param {Function} fn
* @api public
*/
Client.prototype.getFile = function(filename, dest, headers, fn) {
var self = this;
var emitter = new Emitter;

if ('function' == typeof headers) {
fn = headers;
headers = {};
}

self.getStream(filename, headers, function (err, resp) {
if (err) return fn(err);
if (resp.statusCode !== 200) return fn(new Error("http statusCode " + resp.statusCode));
var amountDone = 0;
var amountTotal = parseInt(resp.headers['content-length'], 10);
var writeStream = fs.createWriteStream(dest);
function removeListeners() {
writeStream.removeListener('error', onError);
resp.removeListener('error', onError);
resp.removeListener('end', onSuccess);
}
function onSuccess() {
writeStream.end();
removeListeners();
fn();
}
function onError(err) {
removeListeners();
fn(err);
}
function onData(data) {
amountDone += data.length;
emitter.emit('progress', amountDone, amountTotal);
}
writeStream.on('error', onError);
resp.on('error', onError);
resp.on('end', onSuccess);
resp.on('data', onData);
resp.pipe(writeStream);
});

return emitter;
}

/**
* Issue a HEAD request on `filename` with optional `headers.
*
Expand Down Expand Up @@ -577,7 +629,7 @@ Client.prototype.list = function(params, headers, fn){

var url = params ? '?' + qs.stringify(params) : '';

this.getFile(url, headers, function(err, res){
this.getStream(url, headers, function(err, res){
if (err) return fn(err);

var xmlStr = '';
Expand Down