Getting Started
Dieser Inhalt ist in Ihrer Sprache noch nicht verfügbar.
-
Install the package
Terminal-Fenster npm i @capgo/capacitor-fileTerminal-Fenster pnpm add @capgo/capacitor-fileTerminal-Fenster yarn add @capgo/capacitor-fileTerminal-Fenster bun add @capgo/capacitor-file -
Sync with native projects
Terminal-Fenster npx cap syncTerminal-Fenster pnpm cap syncTerminal-Fenster yarn cap syncTerminal-Fenster bunx cap sync
Usage
Import the plugin and use its methods for file operations:
import { CapacitorFile, Directory, Encoding } from '@capgo/capacitor-file';
// Write a text fileconst writeFile = async () => { const result = await CapacitorFile.writeFile({ path: 'my-file.txt', directory: Directory.Documents, data: 'Hello, World!', encoding: Encoding.UTF8, recursive: true, // Create parent directories if needed }); console.log('File written to:', result.uri);};
// Read a text fileconst readFile = async () => { const result = await CapacitorFile.readFile({ path: 'my-file.txt', directory: Directory.Documents, encoding: Encoding.UTF8, }); console.log('File contents:', result.data);};
// Check if file existsconst checkExists = async () => { const result = await CapacitorFile.exists({ path: 'my-file.txt', directory: Directory.Documents, }); console.log('File exists:', result.exists);};
// Delete a fileconst deleteFile = async () => { await CapacitorFile.deleteFile({ path: 'my-file.txt', directory: Directory.Documents, });};Directory Locations
The plugin provides several directory constants:
import { Directory } from '@capgo/capacitor-file';
// Available directoriesDirectory.Documents // User-visible documents (backed up)Directory.Data // Private app data storageDirectory.Library // App support files (iOS) / files (Android)Directory.Cache // Temporary cache (may be cleared by OS)Directory.External // External storage (Android only)Directory.Application // Read-only app bundleEncoding Options
import { Encoding } from '@capgo/capacitor-file';
Encoding.UTF8 // UTF-8 text encodingEncoding.ASCII // ASCII text encodingEncoding.UTF16 // UTF-16 text encoding// Omit encoding for binary data (returns base64)API Reference
writeFile(options)
Write data to a file.
const result = await CapacitorFile.writeFile({ path: 'folder/file.txt', directory: Directory.Documents, data: 'File content', encoding: Encoding.UTF8, recursive: true, // Create directories if needed append: false, // Overwrite existing file position: 0, // Byte position for random access writes});// Returns: { uri: string }readFile(options)
Read a file’s contents.
const result = await CapacitorFile.readFile({ path: 'file.txt', directory: Directory.Documents, encoding: Encoding.UTF8, offset: 0, // Start reading from byte offset length: 100, // Read only this many bytes});// Returns: { data: string }appendFile(options)
Append data to a file.
await CapacitorFile.appendFile({ path: 'file.txt', directory: Directory.Documents, data: '\nNew line', encoding: Encoding.UTF8,});deleteFile(options)
Delete a file.
await CapacitorFile.deleteFile({ path: 'file.txt', directory: Directory.Documents,});mkdir(options)
Create a directory.
await CapacitorFile.mkdir({ path: 'my-folder/sub-folder', directory: Directory.Documents, recursive: true, // Create parent directories});rmdir(options)
Delete a directory.
await CapacitorFile.rmdir({ path: 'my-folder', directory: Directory.Documents, recursive: true, // Delete contents recursively});readdir(options)
List directory contents.
const result = await CapacitorFile.readdir({ path: '', // Empty for root of directory directory: Directory.Documents,});// Returns: { entries: Entry[] }// Each entry has: { name, isFile, isDirectory, fullPath, nativeURL }stat(options)
Get file or directory metadata.
const result = await CapacitorFile.stat({ path: 'file.txt', directory: Directory.Documents,});// Returns: { type, size, mtime, ctime, uri }exists(options)
Check if a file or directory exists.
const result = await CapacitorFile.exists({ path: 'file.txt', directory: Directory.Documents,});// Returns: { exists: boolean, type?: 'file' | 'directory' }copy(options)
Copy a file or directory.
const result = await CapacitorFile.copy({ from: 'source.txt', to: 'destination.txt', directory: Directory.Documents, toDirectory: Directory.Documents,});// Returns: { uri: string }rename(options) / move(options)
Rename or move a file or directory.
await CapacitorFile.rename({ from: 'old-name.txt', to: 'new-name.txt', directory: Directory.Documents, toDirectory: Directory.Documents,});truncate(options)
Truncate a file to a specific size.
await CapacitorFile.truncate({ path: 'file.txt', directory: Directory.Documents, size: 100, // Truncate to 100 bytes});getUri(options)
Get the native URI for a file.
const result = await CapacitorFile.getUri({ path: 'file.txt', directory: Directory.Documents,});// Returns: { uri: string }getDirectories()
Get all available directory paths.
const dirs = await CapacitorFile.getDirectories();// Returns paths for: documents, data, cache, external, etc.getFreeDiskSpace()
Get available disk space.
const result = await CapacitorFile.getFreeDiskSpace();console.log('Free space:', result.free, 'bytes');checkPermissions() / requestPermissions()
Handle storage permissions (Android).
const status = await CapacitorFile.checkPermissions();if (status.publicStorage !== 'granted') { await CapacitorFile.requestPermissions();}Complete Example
import { CapacitorFile, Directory, Encoding } from '@capgo/capacitor-file';
export class FileService { async saveJson(filename: string, data: object): Promise<void> { await CapacitorFile.writeFile({ path: filename, directory: Directory.Documents, data: JSON.stringify(data, null, 2), encoding: Encoding.UTF8, recursive: true, }); }
async loadJson<T>(filename: string): Promise<T | null> { try { const { exists } = await CapacitorFile.exists({ path: filename, directory: Directory.Documents, });
if (!exists) return null;
const result = await CapacitorFile.readFile({ path: filename, directory: Directory.Documents, encoding: Encoding.UTF8, });
return JSON.parse(result.data) as T; } catch (error) { console.error('Failed to load JSON:', error); return null; } }
async listFiles(folder: string = ''): Promise<string[]> { const result = await CapacitorFile.readdir({ path: folder, directory: Directory.Documents, });
return result.entries .filter(entry => entry.isFile) .map(entry => entry.name); }
async deleteAll(folder: string): Promise<void> { const { exists } = await CapacitorFile.exists({ path: folder, directory: Directory.Documents, });
if (exists) { await CapacitorFile.rmdir({ path: folder, directory: Directory.Documents, recursive: true, }); } }
async copyToBackup(filename: string): Promise<string> { const timestamp = Date.now(); const backupName = `backup/${timestamp}-${filename}`;
const result = await CapacitorFile.copy({ from: filename, to: backupName, directory: Directory.Documents, toDirectory: Directory.Documents, });
return result.uri; }}Platform Notes
iOS
- Requires iOS 13.0+
- Documents directory is visible in Files app
- Library directory is for app support files
- Cache may be cleared when device storage is low
Android
- Requires Android 6.0 (API 23)+
- External storage requires runtime permissions on older Android versions
- Documents directory maps to app’s files directory
- Use External directory for shared storage access
Web
- Not supported on web platform