question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

download file questions

See original GitHub issue

Hello, I’m implementing a download module, want to try node-fetch and have a few questions:

  1. How can i get the total fileSize so i can implement a progress?
  2. How can i pause/resume/cancel a download?

Thank you!

const fetch = require('node-fetch');
const fs = require('fs');

const url = 'https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940'

async function download() {
  const nfetch = await fetch(url);

  const fileStream = fs.createWriteStream('./octocat.png');
  nfetch.body.pipe(fileStream);

  nfetch.body.on("response", (data) => {
    console.log('response ???');
  });

  nfetch.body.on("data", (chunk) => {
    console.log(chunk.length);
  });

  nfetch.body.on("error", (err) => {
    console.log('err:', err)
  });

  fileStream.on("finish", function () {
    console.log('finish');
  });
}

download();

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:12 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
jimmywartingcommented, Aug 15, 2020

here is some psudo code of how to write a downloader that can monitor progress, abort and resume

ctrl = new AbortController()
signal = ctrl.signal
url = 'https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?d='+Date.now()
res = await fetch(url, { signal })
acceptRanges = res.headers.get('accept-ranges') === 'bytes'
contentLength = parseInt(res.headers.get('content-length'))
chunks = []
downloaded = 0

res.body.pipeTo(new WritableStream({
  write(chunk) {
    chunks.push(chunk) // uint8array
    downloaded += chunk.byteLength
    console.log(downloaded, contentLength)
    ctrl.abort()
    console.log(URL.createObjectURL(new Blob(chunks, {type:'image/jpeg'})))
    resumePartialRequest(url, downloaded)
  }
}))

async function resumePartialRequest (url, start = 0, end = '') {
  const res = await fetch(url, {
    headers: {
      'range': `bytes=${start}-${end}` 
    }
  })
  await res.body.pipeTo(new WritableStream({
    write(chunk) {
      chunks.push(chunk)
      downloaded += chunk.byteLength
      console.log(downloaded, contentLength)
    }
  }))
  console.log(URL.createObjectURL(new Blob(chunks, {type:'image/jpeg'})))
}

I wrote this in chrome’s devtool, so it’s not 100% adopted for node-fetch with major differences being pipeTo/pipe and node/whatwg WritableStream Note that there is a lot more to it. You have to check if it accepts byte ranges, you should pipe to some file destination. if it don’t accept byte ranges then you can’t technically “pause & resume” you can only abort then

read more about partial request here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests

1reaction
frvicommented, Apr 16, 2020

For the filesize, you should be able to get it from the content-length response header, e g nfetch.headers.get('content-length');

Read more comments on GitHub >

github_iconTop Results From Across the Web

Insert a Downloadable File - Qualtrics
How To Insert a File · Click on the question text you want to edit. · Click the Rich Content Editor tab. ·...
Read more >
Solved: Download all Files in a File Upload Quiz not Avail...
I've used File Upload questions plenty of times, and the option to Download All Submissions is available (on the front page of the...
Read more >
marking File Response questions - Blackboard Help for Staff
All submitted files are displayed and can be downloaded from here. Download files from File Response question - marking by question. Click Edit ......
Read more >
UiPath Exercise # 57 | Download Multiple Files | By Rakesh
UiPath Exercise # 57 | Download Multiple Files | UiPath Interview Questions | ExpoHub | By Rakesh ... Subscribe for uipath tutorial videos...
Read more >
How to download a file in Selenium WebDriver? (Interview ...
... http://www.evernote.com/l/AbEQHvMA5qRLboLik9bVJLZ8-ICWZeVQJak/In this session, I have answered one of the Selenium Interview Questions ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found