2

I'm using fetch to download a file and there is a problem I'm facing when using fetch that does not happen when I download the file manually on the browser. Maybe I'm missing something here?

the code looks like this:

fetch(link).then(res => {
  let writeStream = fs.createWriteStream(destinationPath)
  writeStream.on('close', callback);

  res.body.pipe(writeStream)
})

Many times the stream just hangs and so I added a settimeout to reattempt download. sometimes it takes many attempts to get it to finish. This does not happen when using the browser (if it does very rarely). Is there some setting that I should adjust for fetch to work properly here? or is my code not correct?

A sample download file is: link

UPDATE: Forgot to mention that I'm using node-fetch on the server.

Thanks!

tito.300
  • 976
  • 1
  • 9
  • 22

1 Answers1

1

If a download works in the browser bar, it doesn't mean it also works with fetch. Their server has to allow cross origin requests if you use fetch.

When using fetch, you can check the response status with the response object.

Bear in mind that fetch doesn't work in node, and fs doesn't work in the browser.

Check fetch status

fetch("https://bulkdata.uspto.gov/data/trademark/dailyxml/applications/apc190416.zip")
.then(res => {
      console.log("download status:")
      console.log(res.ok)
      console.log(res.status)
      return res
    })
Kokodoko
  • 26,167
  • 33
  • 120
  • 197
  • I don't believe the problem is cross origin requests. The file get downloaded sometime. The problem is that sometimes part of it gets downloaded and then it hangs before finishing. Also I forgot to mention I'm using node-fetch package – tito.300 Apr 22 '19 at 16:48