cutFile.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. const CHUNK_SIZE = 1024 * 1024 * 5;
  2. const THREAD_COUNT = navigator.hardwareConcurrency || 4;
  3. export async function cutFile(file){
  4. 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("./worker.js", {
  10. type: "module"
  11. });
  12. let start = i * threadChunkCount;
  13. let end = (i + 1 ) * threadChunkCount;
  14. if(end > chunkCount) end = chunkCount;
  15. worker.postMessage({
  16. file,
  17. chunkSize: CHUNK_SIZE,
  18. startChunkIndex: start,
  19. endChunkIndex: end
  20. })
  21. worker.onmessage = e => {
  22. for(let i = start; i< end; i++){
  23. result[i] = e.data[i - start]
  24. }
  25. worker.terminate();
  26. finishCount++;
  27. if(finishCount === THREAD_COUNT){
  28. resolve(result)
  29. }
  30. }
  31. }
  32. })
  33. }