test-parallel-writes.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* global Blob, FileReader */
  2. import * as zip from "../../index.js";
  3. const KB = 1024;
  4. const ENTRIES_DATA = [
  5. { name: "entry #1", blob: getBlob(8.5 * KB) }, { name: "entry #2", blob: getBlob(5.2 * KB) }, { name: "entry #3", blob: getBlob(4.7 * KB) },
  6. { name: "entry #4", blob: getBlob(2.8 * KB) }, { name: "entry #5", blob: getBlob(1.9 * KB) }, { name: "entry #6", blob: getBlob(2.2 * KB) },
  7. { name: "entry #7", blob: getBlob(5.1 * KB) }, { name: "entry #8", blob: getBlob(2.6 * KB) }, { name: "entry #9", blob: getBlob(3.1 * KB) }];
  8. export { test };
  9. async function test() {
  10. zip.configure({ chunkSize: 128 });
  11. const blobWriter = new zip.BlobWriter("application/zip");
  12. const zipWriter = new zip.ZipWriter(blobWriter);
  13. await Promise.all(ENTRIES_DATA.map(entryData => zipWriter.add(entryData.name, new zip.BlobReader(entryData.blob), { keepOrder: false, bufferedWrite: true, level: Math.random() > .5 ? 5 : 0 })));
  14. await zipWriter.close();
  15. const zipReader = new zip.ZipReader(new zip.BlobReader(blobWriter.getData()));
  16. const entries = await zipReader.getEntries();
  17. const results = await Promise.all(entries.map(async (entry, indexEntry) => {
  18. const blob = await entry.getData(new zip.BlobWriter("application/octet-stream"));
  19. return compareResult(blob, indexEntry);
  20. }));
  21. zip.terminateWorkers();
  22. return !results.includes(false);
  23. }
  24. function compareResult(result, index) {
  25. return new Promise(resolve => {
  26. const fileReaderInput = new FileReader();
  27. const fileReaderOutput = new FileReader();
  28. let loadCount = 0;
  29. fileReaderInput.readAsArrayBuffer(ENTRIES_DATA[index].blob);
  30. fileReaderOutput.readAsArrayBuffer(result);
  31. fileReaderInput.onload = fileReaderOutput.onload = () => {
  32. loadCount++;
  33. if (loadCount == 2) {
  34. const valueInput = new Float64Array(fileReaderInput.result);
  35. const valueOutput = new Float64Array(fileReaderOutput.result);
  36. if (valueInput.length != valueOutput.length) {
  37. resolve(false);
  38. return;
  39. }
  40. for (let indexValue = 0, n = valueInput.length; indexValue < n; indexValue++) {
  41. if (valueInput[indexValue] != valueOutput[indexValue]) {
  42. resolve(false);
  43. return;
  44. }
  45. }
  46. resolve(true);
  47. }
  48. };
  49. });
  50. }
  51. function getBlob(size) {
  52. const data = new Float64Array(Math.floor(size / 8));
  53. for (let indexData = 0; indexData < data.length; indexData++) {
  54. data[indexData] = Math.random();
  55. }
  56. return new Blob([data]);
  57. }