I was trying to access a zip inside my react app without extracting the zip I need to know if a specific file is there inside a zip or not. I don’t want to use any third-party application? Is it possible to get the same in JavaScript?
I have tried to use AdmZip and JSZip library as well but it’s not working. In Adm Zip I’m getting file Module not found: Can’t resolve ‘fs’
In a React application, you can access and check the contents of a ZIP file without extracting it, but there are a few things to keep in mind.
Issue with fs in React:
The error Module not found: Can’t resolve ‘fs’ is because fs (File System) is a Node.js module that doesn’t work in the browser environment. React (and browsers in general) don’t have access to the file system, so libraries like AdmZip that rely on fs will not work in the browser.
Solution using JSZip:
The good news is that JSZip is a pure JavaScript library and should work in the browser. While JSZip can extract files, it can also allow you to check for a specific file inside a ZIP archive without extracting the entire content.
Here’s how you can use JSZip to check if a specific file exists inside a ZIP file in a React app:
Steps:
Install JSZip: First, ensure you have JSZip installed in your project:
npm install jszip
Check if a file exists: You can load the ZIP file, read its contents, and check for a specific file without extracting the whole ZIP.
Example Code:
import JSZip from "jszip";
// Function to check if a specific file exists in the zip
async function checkFileInZip(zipFile) {
try {
const zip = await JSZip.loadAsync(zipFile); // Load the zip file
const fileName = 'path/to/your/file.txt'; // The file you want to check
// Check if the file exists in the zip
if (zip.file(fileName)) {
console.log('File exists in the zip');
} else {
console.log('File not found in the zip');
}
} catch (error) {
console.error('Error reading the zip file:', error);
}
}
// Usage: Example with a file input (you could get the zip from any source)
const inputElement = document.getElementById("zipFileInput");
inputElement.addEventListener("change", (event) => {
const file = event.target.files[0]; // Get the selected zip file
if (file) {
checkFileInZip(file);
}
});