1

I'm trying to download a file with express js, but I'm having some trouble.
Below is the function:

var download = function(uri, filename, callback) {
  request
  .get(uri)
  .on('response', function (response) {
  var ext = response.headers['content-type'].split('/');
  filename += '.' + ext[1];
  })
  .pipe(fs.createWriteStream(filename));
};

The problem is that I don't know the extension of the file, so I need to get it in response headers but the ext[1] value doesn't increment my filename with the file extension. I can't even set a variable by reference to do it outside the function.

Laurel
  • 5,965
  • 14
  • 31
  • 57
Junior Silva
  • 387
  • 5
  • 17

1 Answers1

0
  • I think your pipe is fired before the 'filename' get any data.
  • You should not split with '/'

Try this instead:

var mime = require('mime-types'); // After npm install mime-types

request
    .get(uri)
    .on('response', function (response) {

        var responseType = (response.headers['content-type'] || '').split(';')[0].trim();
        var ext = mime.extension(responseType);

        filename += '.' + ext;

        var fileStream = fs.createWriteStream(filename)
                    .on('finish', function() {
                        //Download complete
                    })

        this.pipe(fileStream);
     })

P.S. You are downloading with 'request' module, not with express.

yeya
  • 1,968
  • 1
  • 21
  • 31
  • Hey yeya! Thanks for your response! Well, i need to get the filename outside the response function, how can i return this filename or set a variable by reference? Thanks again! – Junior Silva Sep 10 '16 at 00:52
  • You can define filename outside the function, but you'll never know when it is changed. NodeJS is async as you know. – yeya Sep 11 '16 at 08:29