cutFile.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. const CHUNK_SIZE = 1024 * 1024 * 5;
  2. const THREAD_COUNT = navigator.hardwareConcurrency || 4;
  3. export async function cutFile(file){
  4. return new Promise((resolve) => {
  5. const chunkCount = Math.ceil(file.size / CHUNK_SIZE);
  6. const threadChunkCount = Math.ceil(chunkCount / THREAD_COUNT);
  7. let result = [], finishCount = 0;
  8. for(let i = 0; i < chunkCount; i++){
  9. const worker = new Worker("node_modules/wxj-tools/tools/worker.js", {
  10. type: "module",
  11. name: "cutFile"
  12. });
  13. let start = i * threadChunkCount;
  14. let end = (i + 1 ) * threadChunkCount;
  15. if(end > chunkCount) end = chunkCount;
  16. worker.postMessage({
  17. file,
  18. chunkSize: CHUNK_SIZE,
  19. startChunkIndex: start,
  20. endChunkIndex: end
  21. })
  22. worker.onmessage = e => {
  23. for(let i = start; i< end; i++){
  24. result[i] = e.data[i - start]
  25. }
  26. worker.terminate();
  27. finishCount++;
  28. if(finishCount === chunkCount){
  29. return resolve(result)
  30. }
  31. }
  32. }
  33. })
  34. }