我目前正在 React Native 中开发一个应用程序来处理文件,其中一些是 zip。
我已经成功使用“react-native-zip-archive”解压缩文件。
有些zip文件包含需要解压才能显示的html文件,有些只是用户可以下载的一些随机zip文件。
我的问题是,我想在解压缩 zip 文件之前知道它的内容(例如所包含文件的列表),以便我只能解压缩其中包含 html 文件的 zip 文件。
有谁知道我可以在 React-Native 中实现这一目标的方法吗?
有一个工具叫node-stream-zip。
这将是我的问题的一个很好的解决方案,但这是一个nodeJS库,似乎在React-Native中使用它是行不通的。
在我的react-native应用程序中使用node-stream-zip会产生此错误:
[错误:未定义无法从node_stream_zip.js解析模块fs:在项目或这些目录中找不到fs: node_modules let fs = require('fs');]
这是我的代码:
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();
}, []);
您可以使用react-native-zip-stream库,它允许您在解压缩ZIP文件之前列出其内容。这样,您可以检查 ZIP 中是否包含任何 HTML 文件并决定是否解压。
您可以使用 listZipContents 列出 ZIP 内的所有文件,并使用 StreamFileFromZip 从 ZIP 流式传输特定文件,例如 HTML 文件。
import { listZipContents, streamFileFromZip } from 'react-native-zip-stream';
const listFilesInZip = async () => {
try {
// List all files in the ZIP
const fileNames = await listZipContents(zipFilePath);
console.log('Files in ZIP:', fileNames);
// Check if the ZIP contains the HTML file
if (fileNames.includes(targetFile)) {
console.log(`${targetFile} found. Streaming content...`);
streamFileContent(targetFile);
} else {
console.log(`${targetFile} not found in the ZIP.`);
}
} catch (error) {
console.error('Error listing ZIP contents:', error);
}
};
const streamFileContent = async (fileName) => {
try {
// Stream the specific file from the ZIP in string format
const fileContent = await streamFileFromZip(zipFilePath, fileName, 'string');
console.log('File Content:', fileContent);
} catch (error) {
console.error('Error streaming file:', error);
}
};
// Call the function
listFilesInZip();
工作原理: listZipContents:列出 ZIP 内的所有文件而不解压缩它。您可以使用它来检查 ZIP 是否包含任何 HTML 文件,例如 index.html。 StreamFileFromZip:直接从 ZIP 流式传输特定文件的内容。如果您只需要某些文件并且不想提取整个存档,这会很有帮助。
有一个工具叫node-stream-zip。
它可以提取并读取zip文件。
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;
}