0

I need to download a big file from remote server ( for example: from amazon ) But I have very bad internet connection, so it can disconnect for some seconds and automatically reconnect, but in this case downloading freezes and I can't catch this event programatically. I use code very similar to this:

const request = require('request')
request({
  uri: `${pathToRemoteFile}`,
  encoding: null
}).on('error', err => console.log(err)) // I suppose that here I will catch all possible errors like internet disconnect, but seems like no
.pipe(fs.createWriteStream(`${pathToStoreFileLocally}`))
.on('finish', () => { console.log('yeah, successfully downloaded') })
.on('error', err => console.log(err))

So for example if I need to download 500MB file, and I have already downloaded for example 100MB and suddenly I lost internet connection so the file will not be downloaded anymore and no errors will raise.

please help

Dengue
  • 113
  • 1
  • 6

1 Answers1

1

I found the solution which is appropriate for myself. here is the code which helps me to set timeout on such a long request.

const request = require('request')
request({
  uri: `${pathToRemoteFile}`,
  encoding: null
}).on('error', err => console.log(err))
.on('socket', socket => {
   socket.setTimeout(30000);
   socket.on('timeout', () => {
      //handle disconnect
   })
 })
.pipe(fs.createWriteStream(`${pathToStoreFileLocally}`))
.on('finish', () => { console.log('yeah, successfully downloaded') })
.on('error', err => console.log(err))

So the part that I was looking for is:

 .on('socket', socket => {
   socket.setTimeout(30000);
   socket.on('timeout', () => {
      //handle disconnect
   })
 })

on the request stream. So timeout event will be raised after 30 seconds of idle on socket

Dengue
  • 113
  • 1
  • 6