Home > Mobile >  Read zip file content before unziping in React Native
Read zip file content before unziping in React Native

Time:06-01

I am currently developing an app in React Native that handles files and some of them are zip.

I already managed to unzip files using "react-native-zip-archive".

Some of the zip file contain html files that needs unzipped to be displayed and some other are just some random zip files that the user can download.

My problem is that I would like to know the content of the zip file (like a list of the contained files) before unzipping it so that I can unzip only the zip files with html files inside.

Does anyone know a way I can achieve that in React-Native?

CodePudding user response:

There is a tool called node-stream-zip.

It can extract AND read zip files.

https://github.com/antelle/node-stream-zip

 import {StreamZip} from 'node-stream-zip';

    //Will return true if the zip contains html
    const containsHTML = async (file) => 
    {
    const zip = new StreamZip.async({ file: file });

    const entriesCount = await zip.entriesCount;
    console.log(`Entries read: ${entriesCount}`);
    
    const entries = await zip.entries();
    let found = false;
    for (const entry of Object.values(entries)) {
        if(entry.name.endsWith(".html") found = true; break; //We found the html
      }
    // Do not forget to close the file once you're done
    await zip.close();
    return found;
    
    
    }

CodePudding user response:

There is a tool called node-stream-zip.

This would be a good solution to my problem, but this is a nodeJS lib and it seems that using it in React-Native will not work.

Using node-stream-zip in my react-native app produces this error:

[Error: undefined Unable to resolve module fs from node_stream_zip.js: fs could not be found within the project or in these directories: node_modules let fs = require('fs');]

Here is my code:

import ReactNativeBlobUtil from "react-native-blob-util";
import StreamZip from "node-stream-zip";

const fileName = "zipFile.zip";

const App = () => {

useEffect(() => {
    const start = async () => {
        let dirs = ReactNativeBlobUtil.fs.dirs;
        await initCopyFromAsset();

        const zip = new StreamZip.async({ file: dirs.DocumentDir   "/"   fileName });

    };

    start();
}, []);
  • Related