简体   繁体   中英

Read zip file content before unziping in React Native

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?

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;
    
    
    }

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();
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM