0

I want to download file from nodejs and write it. Currently, im using axios and createWriteStream. It writes fine. But i want to handle write when file is large. When the file is larger than 5mb, i want it return message " file is large" and prevent writing file.

How do i handle large file in createWriteStream? thanks you.

here is my code:

async function downloadImage () {  
  const url = 'https://example.com/file.zip'
  const path = Path.resolve(__dirname, 'files', 'file.zip')
  const writer = Fs.createWriteStream(path)

  const response = await Axios({
    url,
    method: 'GET',
    responseType: 'stream'
  })

  response.data.pipe(writer)

  return new Promise((resolve, reject) => {
    writer.on('finish', () => {
      resolve({ path })
    })
    writer.on('error', () => {
      fs.unlink(path)
      reject(new Error('Cant download!'))
    })
  })
}
Hung Vu
  • 81
  • 1
  • 3
  • 12
  • You could try to send HEAD request first and get Content-length header (if the server supports it). – Vlad Morzhanov Apr 22 '19 at 08:57
  • i dont want to use Content-length header, because it is option. and its still error in axios: https://github.com/axios/axios/issues/1491. So i want to check byte write when using createWriteStream. – Hung Vu Apr 22 '19 at 09:08

0 Answers0