1. /**
  2. * Converts binary files to different formats for staging environments,
  3. * with fallback logic.
  4. *
  5. * @param {File} file The binary file to convert.
  6. * @param {string} targetFormat The desired target format ('raw', 'gzip', 'bzip2'). Defaults to 'raw'.
  7. * @returns {Promise<ArrayBuffer|null>} A Promise that resolves with the converted ArrayBuffer,
  8. * or null if conversion fails.
  9. */
  10. async function convertBinaryFile(file, targetFormat = 'raw') {
  11. return new Promise((resolve, reject) => {
  12. if (!file) {
  13. console.error("No file provided.");
  14. resolve(null);
  15. return;
  16. }
  17. const reader = new FileReader();
  18. reader.onload = (event) => {
  19. const contents = event.target.result;
  20. try {
  21. switch (targetFormat) {
  22. case 'raw':
  23. resolve(contents);
  24. break;
  25. case 'gzip':
  26. const compressed = pako.gzip(contents); // Requires pako library
  27. resolve(compressed);
  28. break;
  29. case 'bzip2':
  30. const compressed = pako.bzip2(contents); // Requires pako library
  31. resolve(compressed);
  32. break;
  33. default:
  34. console.warn(`Unsupported target format: ${targetFormat}. Falling back to raw.`);
  35. resolve(contents);
  36. }
  37. } catch (error) {
  38. console.error("Conversion error:", error);
  39. resolve(null); // Resolve with null on error
  40. }
  41. };
  42. reader.onerror = (error) => {
  43. console.error("File read error:", error);
  44. resolve(null); // Resolve with null on error
  45. };
  46. reader.readAsArrayBuffer(file); // Read the file as an ArrayBuffer
  47. });
  48. }

Add your comment