Skip to content

Commit

Permalink
build res.download() on top of res.sendfile()
Browse files Browse the repository at this point in the history
like it should have always been
  • Loading branch information
tj committed Aug 18, 2011
1 parent 7a476fc commit d3ccdbc
Showing 1 changed file with 24 additions and 41 deletions.
65 changes: 24 additions & 41 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,30 @@ res.sendfile = function(path, options, fn){
send(this.req, this, next, options);
};

/**
* Transfer the file at the given `path` as an attachment.
*
* Optionally providing an alternate attachment `filename`,
* and optional callback `fn(err)`. The callback is invoked
* when the data transfer is complete, or when an error has
* ocurred. Be sure to check `res.sendHeader` if you plan to respond.
*
* @param {String} path
* @param {String|Function} filename or fn
* @param {Function} fn
* @api public
*/

res.download = function(path, filename, fn){
// support function as second arg
if ('function' == typeof filename) {
fn = filename;
filename = null;
}

return this.attachment(filename || path).sendfile(path, fn);
};

/**
* Set _Content-Type_ response header passed through `mime.lookup()`.
*
Expand Down Expand Up @@ -239,47 +263,6 @@ res.attachment = function(filename){
return this;
};

/**
* Transfer the file at the given `path`, with optional
* `filename` as an attachment and optional callback `fn(err)`,
* and optional `fn2(err)` which is invoked when an error has
* occurred after header has been sent.
*
* @param {String} path
* @param {String|Function} filename or fn
* @param {Function} fn
* @param {Function} fn2
* @api public
*/

res.download = function(path, filename, fn, fn2){
var self = this;

// support callback as second arg
if ('function' == typeof filename) {
fn2 = fn;
fn = filename;
filename = null;
}

// transfer the file
this.attachment(filename || path).sendfile(path, function(err){
var sentHeader = self._header;
if (err) {
if (!sentHeader) self.removeHeader('Content-Disposition');
if (sentHeader) {
fn2 && fn2(err);
} else if (fn) {
fn(err);
} else {
self.req.next(err);
}
} else if (fn) {
fn();
}
});
};

/**
* Set header `field` to `val`.
*
Expand Down

0 comments on commit d3ccdbc

Please sign in to comment.