user3019326 user3019326 - 1 year ago 196
Node.js Question

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:


Where I want to do (pseudocode):

var req = request('');
var filename = req.response.headers['Content-Disposition'];


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?

Answer Source

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 = '';

var r = request(url2);

r.on('response',  function (res) {
  res.pipe(fs.createWriteStream('./' + + '.' + res.headers['content-type'].split('/')[1]));


Ignore my image choice please :)