/**
* Converts binary files to different formats for staging environments,
* with fallback logic.
*
* @param {File} file The binary file to convert.
* @param {string} targetFormat The desired target format ('raw', 'gzip', 'bzip2'). Defaults to 'raw'.
* @returns {Promise<ArrayBuffer|null>} A Promise that resolves with the converted ArrayBuffer,
* or null if conversion fails.
*/
async function convertBinaryFile(file, targetFormat = 'raw') {
return new Promise((resolve, reject) => {
if (!file) {
console.error("No file provided.");
resolve(null);
return;
}
const reader = new FileReader();
reader.onload = (event) => {
const contents = event.target.result;
try {
switch (targetFormat) {
case 'raw':
resolve(contents);
break;
case 'gzip':
const compressed = pako.gzip(contents); // Requires pako library
resolve(compressed);
break;
case 'bzip2':
const compressed = pako.bzip2(contents); // Requires pako library
resolve(compressed);
break;
default:
console.warn(`Unsupported target format: ${targetFormat}. Falling back to raw.`);
resolve(contents);
}
} catch (error) {
console.error("Conversion error:", error);
resolve(null); // Resolve with null on error
}
};
reader.onerror = (error) => {
console.error("File read error:", error);
resolve(null); // Resolve with null on error
};
reader.readAsArrayBuffer(file); // Read the file as an ArrayBuffer
});
}
Add your comment