New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use angular 2+ http service or fetch API to download files to use browser and OS proxy settings #1052

Open
dgolovin opened this Issue Nov 22, 2017 · 0 comments

Comments

Projects
None yet
1 participant
@dgolovin
Contributor

dgolovin commented Nov 22, 2017

Now installer uses request node module to download resources and send http requests. It does not use OS and browser proxy settings by default and therefore to work behind proxy manually setting HTTPS_PROXY env variable is required.

Here is fixed example from https://damieng.com/blog/2017/03/10/downloading-files-with-progress-in-electron that uses fetch API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch to download files.

import fs from 'fs';

async function download(sourceUrl, targetFile, progressCallback, length) {
  const request = new Request(sourceUrl, {
    headers: new Headers({'Content-Type': 'application/octet-stream'})
  });

  const response = await fetch(request);
  if (!response.ok) throw Error(`Unable to download, server returned ${response.status} ${response.statusText}`);

  const body = response.body;
  if (body == null) throw Error('No response body');

  const finalLength = length || parseInt(response.headers.get('Content-Length' || '0'), 10);
  const reader = body.getReader();
  const writer = fs.createWriteStream(targetFile);

  await streamWithProgress(finalLength, reader, writer, progressCallback);
  writer.end();
}

async function streamWithProgress(length, reader, writer, progressCallback) {
  let bytesDone = 0;

  while (true) {
    const result = await reader.read();
    if (result.done) {
      console.log(result);
      if (progressCallback != null) {
        progressCallback(length, 100);
      }
      return;
    }

    writer.write(Buffer.from(result.value));
    if (progressCallback != null) {
      bytesDone += result.value.byteLength;
      const percent = length === 0 ? null : Math.floor(bytesDone / length * 100);
      progressCallback(bytesDone, percent);
    }
  }
}

module.exports = download
Downloader('https://developers.redhat.com/redirect/to/virtualbox-windows-5.1.24.download', 'c:\\Temp\\vp.exe',
   (bytes, percent) => console.log(`Downloaded ${bytes} (${percent})`));
    this.router.go('location');
  }

fetch API though required to implement custom timeout and request termination.

@dgolovin dgolovin self-assigned this Nov 22, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment