CodeWithYou

Show a progress bar when downloading files in Node.js

Published on
Authors

When downloading files from the Internet, you should reach for a streaming download. Streams are great to handle large files by chunking them into small pieces and downloading the files as individual chunks. And maybe you want to show a progress bar while downloading the file.

In this article, I will show you how to show a progress bar while downloading a file. I will use the progress package to do that.

const download = async (url) => {
  console.log('Connecting …')
  const { data, headers } = await axios({
    url,
    method: 'GET',
    responseType: 'stream',
  })
  const totalLength = headers['content-length']

  console.log('Starting download')
  const progressBar = new ProgressBar('-> downloading [:bar] :percent :etas', {
    width: 40,
    complete: '=',
    incomplete: ' ',
    renderThrottle: 1,
    total: parseInt(totalLength),
  })

  const writer = fs.createWriteStream(path.resolve(__dirname, 'download', 'BigBuckBunny.mp4'))

  data.on('data', (chunk) => progressBar.tick(chunk.length))
  data.pipe(writer)
}

(async () => {
  await download(
    'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'
  )
})()
Connecting …
Starting download
-> downloading [=============================           ] 73% 1.4s

Notes:

  1. Some servers don’t set the content-length header accordingly. They may use a different response header instead.
  2. Axios has a built-in onDownloadProgress event. This event is only available in the browser. So when use axios in node.js you must implement the progress handling yourself

Source code of this article is available github

Advertisement