ReaderWorker.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const workerState = require('./workerState');
  2. const utils = require('./utils');
  3. const fs = require('fs-extra');
  4. const util = require('util');
  5. const stream = require('stream');
  6. const pipeline = util.promisify(stream.pipeline);
  7. const download = require('download');
  8. class ReaderWorker {
  9. constructor(config) {
  10. this.config = config;
  11. this.tempDownloadDir = `${config.tempDir}/download`;
  12. fs.ensureDirSync(this.tempDownloadDir);
  13. }
  14. async loadBook(wState, url) {
  15. try {
  16. wState.set({state: 'download', step: 1, totalSteps: 3, url});
  17. const tempFilename = utils.randomHexString(30);
  18. const d = download(url);
  19. d.on('downloadProgress', progress => {
  20. wState.set({progress: Math.round(progress.percent*100)});
  21. })
  22. await pipeline(d, fs.createWriteStream(`${this.tempDownloadDir}/${tempFilename}`));
  23. wState.finish({step: 3, file: tempFilename});
  24. } catch (e) {
  25. wState.set({state: 'error', error: e.message});
  26. }
  27. }
  28. loadBookUrl(url) {
  29. const workerId = workerState.generateWorkerId();
  30. const wState = workerState.getControl(workerId);
  31. wState.set({state: 'start'});
  32. this.loadBook(wState, url);
  33. return workerId;
  34. }
  35. }
  36. module.exports = ReaderWorker;