FileDownloader.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const got = require('got');
  2. class FileDownloader {
  3. constructor(limitDownloadSize = 0) {
  4. this.limitDownloadSize = limitDownloadSize;
  5. }
  6. async load(url, callback, abort) {
  7. let errMes = '';
  8. const options = {
  9. encoding: null,
  10. headers: {
  11. 'user-agent': 'Mozilla/5.0 (X11; HasCodingOs 1.0; Linux x64) AppleWebKit/637.36 (KHTML, like Gecko) Chrome/70.0.3112.101 Safari/637.36 HasBrowser/5.0'
  12. }
  13. };
  14. const response = await got(url, Object.assign({}, options, {method: 'HEAD'}));
  15. let estSize = 0;
  16. if (response.headers['content-length']) {
  17. estSize = response.headers['content-length'];
  18. }
  19. let prevProg = 0;
  20. const request = got(url, options);
  21. request.on('downloadProgress', progress => {
  22. if (this.limitDownloadSize) {
  23. if (progress.transferred > this.limitDownloadSize) {
  24. errMes = 'Файл слишком большой';
  25. request.cancel();
  26. }
  27. }
  28. let prog = 0;
  29. if (estSize)
  30. prog = Math.round(progress.transferred/estSize*100);
  31. else if (progress.transferred)
  32. prog = Math.round(progress.transferred/(progress.transferred + 200000)*100);
  33. if (prog != prevProg && callback)
  34. callback(prog);
  35. prevProg = prog;
  36. if (abort && abort()) {
  37. errMes = 'abort';
  38. request.cancel();
  39. }
  40. });
  41. try {
  42. return (await request).body;
  43. } catch (error) {
  44. errMes = (errMes ? errMes : error.message);
  45. throw new Error(errMes);
  46. }
  47. }
  48. }
  49. module.exports = FileDownloader;