developer-platform-install icon indicating copy to clipboard operation
developer-platform-install copied to clipboard

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

Open dgolovin opened this issue 8 years ago • 0 comments

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 avatar Nov 22 '17 03:11 dgolovin