sigit.io/src/utils/zip.ts

55 lines
1.6 KiB
TypeScript
Raw Normal View History

import JSZip from 'jszip'
import { toast } from 'react-toastify'
import { InputFileFormat, OutputByType, OutputType } from '../types'
/**
* Read the content of a file within a zip archive.
* @param zip The JSZip object representing the zip archive.
* @param filePath The path of the file within the zip archive.
* @param outputType The type of output to return (e.g., 'string', 'arraybuffer', 'uint8array', etc.).
* @returns A Promise resolving to the content of the file, or null if an error occurs.
*/
const readContentOfZipEntry = async <T extends OutputType>(
zip: JSZip,
filePath: string,
outputType: T
): Promise<OutputByType[T] | null> => {
// Get the zip entry corresponding to the specified file path
const zipEntry = zip.files[filePath]
if (!zipEntry) {
toast.error(`Couldn't find file in zip archive at ${filePath}`)
return null
}
// Read the content of the zip entry asynchronously
const fileContent = await zipEntry.async(outputType).catch((err) => {
// Handle any errors that occur during the read operation
console.log(`Error reading content of ${filePath}:`, err)
toast.error(
err.message || `Error occurred in reading content of ${filePath}`
)
return null
})
// Return the file content or null if an error occurred
return fileContent
}
const loadZip = async (data: InputFileFormat): Promise<JSZip | null> => {
try {
return await JSZip.loadAsync(data);
} catch (err: any) {
console.log('err in loading zip file :>> ', err)
toast.error(err.message || 'An error occurred in loading zip file.')
return null;
}
}
export {
readContentOfZipEntry,
loadZip
}