Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Download File Using Content Disposition as Filename

I'm using the Request module to download files, but I'm not quite sure how to pipe the response to an output stream when the filename must come from the 'Content-Disposition' header. So basically, I need to read the response until the header is found, and then pipe the rest to that filename.

The examples show something like:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'));

Where I want to do (pseudocode):

var req = request('http://example.com/download_latest_version?token=XXX'); var filename = req.response.headers['Content-Disposition'];  req.pipe(fs.createWriteStream(filename)); 

I could get the filename using the Request callback:

request(url, function(err, res, body) {  // get res headers here }); 

But wouldn't that negate the benefits of using pipe and not loading the downloaded file into memory?

like image 229
user3019326 Avatar asked Nov 21 '13 21:11

user3019326


1 Answers

I'm reqesting a image from yahoo and it isn't using the content-disposition header but I am extracting the date and content-type headers to construct a filename. This seems close enough to what you're trying to do...

var request = require('request'), fs = require('fs');  var url2 = 'http://l4.yimg.com/nn/fp/rsz/112113/images/smush/aaroncarter_635x250_1385060042.jpg';  var r = request(url2);  r.on('response',  function (res) {   res.pipe(fs.createWriteStream('./' + res.headers.date + '.' + res.headers['content-type'].split('/')[1]));  }); 

Ignore my image choice please :)

like image 184
kberg Avatar answered Oct 19 '22 03:10

kberg