Erste Schritte
Copy a setup prompt with the install steps and the full markdown guide for this plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-zip`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/de/docs/plugins/zip/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
-
Paket installieren
Terminal-Fenster npm i @capgo/capacitor-zipTerminal-Fenster pnpm add @capgo/capacitor-zipTerminal-Fenster yarn add @capgo/capacitor-zipTerminal-Fenster bun add @capgo/capacitor-zip -
Mit nativen Projekten synchronisieren
Terminal-Fenster npx cap syncTerminal-Fenster pnpm cap syncTerminal-Fenster yarn cap syncTerminal-Fenster bunx cap sync
Nutzung
Section titled “Nutzung”Importieren Sie das Plugin und komprimieren oder entpacken Sie die Dateien:
import { CapacitorZip } from '@capgo/capacitor-zip';
// Zip a folderconst zipFolder = async () => { await CapacitorZip.zip({ source: 'file:///path/to/folder', destination: 'file:///path/to/archive.zip' }); console.log('Folder zipped successfully!');};
// Unzip an archiveconst unzipArchive = async () => { await CapacitorZip.unzip({ source: 'file:///path/to/archive.zip', destination: 'file:///path/to/output/folder' }); console.log('Archive extracted successfully!');};API Referenz
Section titled “API Referenz”zip(Optionen)
Section titled “zip(Optionen)”Erstellt ein ZIP-Archiv aus einem Quellordner.
interface ZipOptions { source: string; // Path to folder to compress destination: string; // Path for output ZIP file}
await CapacitorZip.zip({ source: 'file:///path/to/folder', destination: 'file:///path/to/archive.zip'});entpacken(Optionen)
Section titled “entpacken(Optionen)”Extrahiert Dateien aus einem ZIP-Archiv.
interface UnzipOptions { source: string; // Path to ZIP file destination: string; // Path to extract to}
await CapacitorZip.unzip({ source: 'file:///path/to/archive.zip', destination: 'file:///path/to/output/folder'});Vollständiges Beispiel
Section titled “Vollständiges Beispiel”import { CapacitorZip } from '@capgo/capacitor-zip';import { Filesystem, Directory } from '@capacitor/filesystem';
export class ZipService { async createBackup() { try { const timestamp = Date.now(); const sourceDir = `${Filesystem.Directory.Data}/userdata`; const destPath = `${Filesystem.Directory.Documents}/backup_${timestamp}.zip`;
await CapacitorZip.zip({ source: sourceDir, destination: destPath });
console.log('Backup created:', destPath); return destPath; } catch (error) { console.error('Backup failed:', error); throw error; } }
async restoreBackup(backupPath: string) { try { const destDir = `${Filesystem.Directory.Data}/userdata`;
// Clear existing data await Filesystem.rmdir({ path: 'userdata', directory: Directory.Data, recursive: true });
// Extract backup await CapacitorZip.unzip({ source: backupPath, destination: destDir });
console.log('Backup restored successfully'); } catch (error) { console.error('Restore failed:', error); throw error; } }
async compressFiles(filePaths: string[], outputPath: string) { try { // Create temporary directory const tempDir = `${Filesystem.Directory.Cache}/temp_zip_${Date.now()}`;
await Filesystem.mkdir({ path: tempDir, directory: Directory.Cache, recursive: true });
// Copy files to temp directory for (const filePath of filePaths) { const fileName = filePath.split('/').pop(); await Filesystem.copy({ from: filePath, to: `${tempDir}/${fileName}` }); }
// Zip the temp directory await CapacitorZip.zip({ source: tempDir, destination: outputPath });
// Clean up temp directory await Filesystem.rmdir({ path: tempDir, directory: Directory.Cache, recursive: true });
return outputPath; } catch (error) { console.error('Compression failed:', error); throw error; } }
async extractSpecificFiles(zipPath: string, fileNames: string[]) { try { // Extract to temp location const tempDir = `${Filesystem.Directory.Cache}/temp_extract_${Date.now()}`;
await CapacitorZip.unzip({ source: zipPath, destination: tempDir });
// Read only specific files const extractedFiles: { [key: string]: string } = {};
for (const fileName of fileNames) { const content = await Filesystem.readFile({ path: `${tempDir}/${fileName}`, directory: Directory.Cache }); extractedFiles[fileName] = content.data; }
// Clean up await Filesystem.rmdir({ path: tempDir, directory: Directory.Cache, recursive: true });
return extractedFiles; } catch (error) { console.error('Extraction failed:', error); throw error; } }}Erweiterte Nutzung
Section titled “Erweiterte Nutzung”Erstellen von Archiven mit Fortschrittsverfolgung
Section titled “Erstellen von Archiven mit Fortschrittsverfolgung”const zipWithProgress = async (source: string, destination: string) => { console.log('Starting compression...');
try { await CapacitorZip.zip({ source, destination }); console.log('Compression complete!'); } catch (error) { console.error('Compression failed:', error); throw error; }};Batch-Archivierungsvorgänge
Section titled “Batch-Archivierungsvorgänge”const batchZip = async (folders: string[]) => { const results = [];
for (const folder of folders) { const folderName = folder.split('/').pop(); const zipPath = `${folder}_${Date.now()}.zip`;
try { await CapacitorZip.zip({ source: folder, destination: zipPath }); results.push({ folder, zipPath, success: true }); } catch (error) { results.push({ folder, error, success: false }); } }
return results;};Sichere Archiverstellung
Section titled “Sichere Archiverstellung”const createSecureBackup = async (dataPath: string) => { // Zip the data const zipPath = `${Filesystem.Directory.Documents}/secure_backup.zip`;
await CapacitorZip.zip({ source: dataPath, destination: zipPath });
// Optionally encrypt the zip file here using a crypto plugin
return zipPath;};Archivvalidierung
Section titled “Archivvalidierung”const validateArchive = async (zipPath: string): Promise<boolean> => { try { const tempDir = `${Filesystem.Directory.Cache}/validate_${Date.now()}`;
// Try to extract await CapacitorZip.unzip({ source: zipPath, destination: tempDir });
// Clean up await Filesystem.rmdir({ path: tempDir, directory: Directory.Cache, recursive: true });
return true; } catch (error) { console.error('Archive validation failed:', error); return false; }};Bewährte Methoden
Section titled “Bewährte Methoden”- Pfadvalidierung: Validieren Sie immer Quell- und Zielpfade vor Vorgängen
- Fehlerbehandlung: Wickeln Sie alle Zip-/Unzip-Vorgänge in Try-Catch-Blöcke ein
- Bereinigung: Entfernen Sie temporäre Dateien und Ordner nach den Vorgängen
- Große Dateien: Seien Sie vorsichtig bei großen Archiven auf Mobilgeräten
- Berechtigungen: Stellen Sie sicher, dass Ihre App über die erforderlichen Dateisystemberechtigungen verfügt
Fehlerbehebung
Section titled “Fehlerbehebung”Häufige Probleme
Section titled “Häufige Probleme”Zip-Vorgang schlägt fehl: Stellen Sie sicher, dass der Quellpfad vorhanden und zugänglich ist Entpacken schlägt fehl: Überprüfen Sie, ob die ZIP-Datei gültig ist und der Zielpfad beschreibbar ist Nicht genügend Speicherplatz: Überwachen Sie den verfügbaren Speicherplatz vor dem Betrieb Berechtigung verweigert: Überprüfen Sie die Dateisystemberechtigungen in Ihrer App-Konfiguration