0

There exists a url which dynamically creates a file (zip) for download. http://example.com/generateZipFile.php

In a browser, opening the url simply opens the download dialog box, and a user can save the file to their hard drive.

I need to automatically download this file using node.js

I have tried the following code:

var file = fs.createWriteStream("http://example.com/generateZip.php");
var request = http.get(URL, function(response) {
    response.pipe(file);
});

However it only downloads the content of what appears to be a HTML redirect page to the current incantation of the zip file, not the zip file itself:

> <head><title>Document Moved</title></head> <body><h1>Object
> Moved</h1>This document may be found <a
> HREF="http://example.com/generated12345.zip">here</a></body>

I can not hard code the generated name of the zip file, as it is subject to change.

Mtl Dev
  • 1,604
  • 20
  • 29

1 Answers1

1

http module does not support redirection for queries. You can use request module:

require('request')
  .get('http://example.com/generateZip.php')
  .on('error', function(error) {
    console.log(error)
  })
  .pipe(require('fs').createWriteStream(__dirname + '/tmp.file'))
stdob--
  • 28,222
  • 5
  • 58
  • 73