33 lines
1.2 KiB
TypeScript
33 lines
1.2 KiB
TypeScript
|
import JSZip from 'jszip'
|
||
|
import { toast } from 'react-toastify'
|
||
|
import { 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.
|
||
|
*/
|
||
|
export 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]
|
||
|
|
||
|
// 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
|
||
|
}
|