FileDownloader.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const got = require('got');
  2. class FileDownloader {
  3. constructor(limitDownloadSize = 0) {
  4. this.limitDownloadSize = limitDownloadSize;
  5. }
  6. async load(url, callback) {
  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).on('downloadProgress', progress => {
  21. if (this.limitDownloadSize) {
  22. if (progress.transferred > this.limitDownloadSize) {
  23. errMes = 'Файл слишком большой';
  24. request.cancel();
  25. }
  26. }
  27. let prog = 0;
  28. if (estSize)
  29. prog = Math.round(progress.transferred/estSize*100);
  30. else if (progress.transferred)
  31. prog = Math.round(progress.transferred/(progress.transferred + 200000)*100);
  32. if (prog != prevProg && callback)
  33. callback(prog);
  34. prevProg = prog;
  35. });
  36. try {
  37. return (await request).body;
  38. } catch (error) {
  39. errMes = (errMes ? errMes : error.message);
  40. throw new Error(errMes);
  41. }
  42. }
  43. }
  44. module.exports = FileDownloader;