@capgo/capacitor-file
v7.1.1
Published
Capacitor plugin for file system operations, compatible with Cordova File plugin API
Maintainers
Readme
@capgo/capacitor-file
Capacitor plugin for file system operations. A modern replacement for cordova-plugin-file with a compatible API.
Why Capacitor File?
A reliable native file system plugin built for Capacitor apps with advanced features not available in the official Filesystem plugin:
- Partial file reading - Read specific portions of files with
offsetandlengthparameters (great for large files) - Random access writes - Write at specific byte positions with
positionparameter - Cordova compatible API - Familiar methods like
requestFileSystem(),resolveLocalFileSystemURL(),getFile(), andgetDirectory() - All platform directories - Access Documents, Library, Cache, External storage and more
- Progress events - Monitor read/write operations with real-time progress updates
- Free and open source - No paid services required
Perfect for apps that need to work with large files, migrate from Cordova, or require random access file operations.
Documentation
The most complete doc is available here: https://capgo.app/docs/plugins/file/
Install
npm install @capgo/capacitor-file
npx cap syncAPI
requestFileSystem(...)resolveLocalFileSystemURL(...)getFile(...)getDirectory(...)readFile(...)readAsDataURL(...)writeFile(...)appendFile(...)deleteFile(...)mkdir(...)rmdir(...)readdir(...)stat(...)getMetadata(...)rename(...)move(...)copy(...)exists(...)getUri(...)truncate(...)getDirectories()getFreeDiskSpace()addListener('readProgress', ...)addListener('writeProgress', ...)removeAllListeners()getPluginVersion()checkPermissions()requestPermissions(...)- Interfaces
- Type Aliases
- Enums
Capacitor File Plugin Implements file system operations similar to the Cordova File plugin
requestFileSystem(...)
requestFileSystem(options: RequestFileSystemOptions) => Promise<FileSystem>Request a file system.
| Param | Type | Description |
| ------------- | ----------------------------------------------------------------------------- | ----------------------------- |
| options | RequestFileSystemOptions | - File system request options |
Returns: Promise<FileSystem>
resolveLocalFileSystemURL(...)
resolveLocalFileSystemURL(options: ResolveURLOptions) => Promise<Entry>Resolve a file URL to an entry.
| Param | Type | Description |
| ------------- | --------------------------------------------------------------- | ---------------- |
| options | ResolveURLOptions | - URL to resolve |
Returns: Promise<Entry>
getFile(...)
getFile(options: GetFileOptions) => Promise<FileEntry>Get a file entry.
| Param | Type | Description |
| ------------- | --------------------------------------------------------- | ----------------------- |
| options | GetFileOptions | - File path and options |
Returns: Promise<FileEntry>
getDirectory(...)
getDirectory(options: GetDirectoryOptions) => Promise<DirectoryEntry>Get a directory entry.
| Param | Type | Description |
| ------------- | ------------------------------------------------------------------- | ----------------------------------------------------- |
| options | GetDirectoryOptions | - Directory path and options |
Returns: Promise<DirectoryEntry>
readFile(...)
readFile(options: ReadFileOptions) => Promise<ReadFileResult>Read a file as text or base64.
| Param | Type | Description |
| ------------- | ----------------------------------------------------------- | -------------- |
| options | ReadFileOptions | - Read options |
Returns: Promise<ReadFileResult>
readAsDataURL(...)
readAsDataURL(options: ReadFileOptions) => Promise<{ data: string; }>Read a file as a data URL (base64 with MIME type prefix).
| Param | Type | Description |
| ------------- | ----------------------------------------------------------- | -------------- |
| options | ReadFileOptions | - Read options |
Returns: Promise<{ data: string; }>
writeFile(...)
writeFile(options: WriteFileOptions) => Promise<WriteFileResult>Write data to a file.
| Param | Type | Description |
| ------------- | ------------------------------------------------------------- | --------------- |
| options | WriteFileOptions | - Write options |
Returns: Promise<WriteFileResult>
appendFile(...)
appendFile(options: WriteFileOptions) => Promise<WriteFileResult>Append data to a file.
| Param | Type | Description |
| ------------- | ------------------------------------------------------------- | ------------------------------------------ |
| options | WriteFileOptions | - Write options (append is forced to true) |
Returns: Promise<WriteFileResult>
deleteFile(...)
deleteFile(options: DeleteFileOptions) => Promise<void>Delete a file.
| Param | Type | Description |
| ------------- | --------------------------------------------------------------- | ---------------- |
| options | DeleteFileOptions | - Delete options |
mkdir(...)
mkdir(options: MkdirOptions) => Promise<void>Create a directory.
| Param | Type | Description |
| ------------- | ----------------------------------------------------- | ----------------------------------------------------- |
| options | MkdirOptions | - Directory creation options |
rmdir(...)
rmdir(options: DeleteDirectoryOptions) => Promise<void>Delete a directory.
| Param | Type | Description |
| ------------- | ------------------------------------------------------------------------- | ---------------- |
| options | DeleteDirectoryOptions | - Delete options |
readdir(...)
readdir(options: ReaddirOptions) => Promise<ReaddirResult>Read directory contents.
| Param | Type | Description |
| ------------- | --------------------------------------------------------- | -------------- |
| options | ReaddirOptions | - Read options |
Returns: Promise<ReaddirResult>
stat(...)
stat(options: StatOptions) => Promise<StatResult>Get metadata about a file or directory.
| Param | Type | Description |
| ------------- | --------------------------------------------------- | -------------- |
| options | StatOptions | - Stat options |
Returns: Promise<StatResult>
getMetadata(...)
getMetadata(options: StatOptions) => Promise<Metadata>Get metadata about a file or directory. Alias for stat().
| Param | Type | Description |
| ------------- | --------------------------------------------------- | -------------- |
| options | StatOptions | - Stat options |
Returns: Promise<Metadata>
rename(...)
rename(options: RenameOptions) => Promise<void>Rename or move a file or directory.
| Param | Type | Description |
| ------------- | ------------------------------------------------------- | ---------------- |
| options | RenameOptions | - Rename options |
move(...)
move(options: RenameOptions) => Promise<void>Move a file or directory. Alias for rename().
| Param | Type | Description |
| ------------- | ------------------------------------------------------- | -------------- |
| options | RenameOptions | - Move options |
copy(...)
copy(options: CopyOptions) => Promise<CopyResult>Copy a file or directory.
| Param | Type | Description |
| ------------- | --------------------------------------------------- | -------------- |
| options | CopyOptions | - Copy options |
Returns: Promise<CopyResult>
exists(...)
exists(options: ExistsOptions) => Promise<ExistsResult>Check if a file or directory exists.
| Param | Type | Description |
| ------------- | ------------------------------------------------------- | --------------- |
| options | ExistsOptions | - Check options |
Returns: Promise<ExistsResult>
getUri(...)
getUri(options: GetUriOptions) => Promise<GetUriResult>Get the URI for a file.
| Param | Type | Description |
| ------------- | ------------------------------------------------------- | ------------- |
| options | GetUriOptions | - URI options |
Returns: Promise<GetUriResult>
truncate(...)
truncate(options: TruncateOptions) => Promise<void>Truncate a file to a specified size.
| Param | Type | Description |
| ------------- | ----------------------------------------------------------- | ------------------ |
| options | TruncateOptions | - Truncate options |
getDirectories()
getDirectories() => Promise<FileDirectories>Get all known file system directories.
Returns: Promise<FileDirectories>
getFreeDiskSpace()
getFreeDiskSpace() => Promise<{ free: number; }>Get the free disk space in bytes.
Returns: Promise<{ free: number; }>
addListener('readProgress', ...)
addListener(eventName: 'readProgress', listenerFunc: (progress: ProgressEvent) => void) => Promise<PluginListenerHandle>Listen for read progress events.
| Param | Type | Description |
| ------------------ | ------------------------------------------------------------------------------ | ------------------------------------- |
| eventName | 'readProgress' | - Must be 'readProgress' |
| listenerFunc | (progress: ProgressEvent) => void | - Callback receiving progress updates |
Returns: Promise<PluginListenerHandle>
addListener('writeProgress', ...)
addListener(eventName: 'writeProgress', listenerFunc: (progress: ProgressEvent) => void) => Promise<PluginListenerHandle>Listen for write progress events.
| Param | Type | Description |
| ------------------ | ------------------------------------------------------------------------------ | ------------------------------------- |
| eventName | 'writeProgress' | - Must be 'writeProgress' |
| listenerFunc | (progress: ProgressEvent) => void | - Callback receiving progress updates |
Returns: Promise<PluginListenerHandle>
removeAllListeners()
removeAllListeners() => Promise<void>Remove all event listeners.
getPluginVersion()
getPluginVersion() => Promise<{ version: string; }>Get the plugin version.
Returns: Promise<{ version: string; }>
checkPermissions()
checkPermissions() => Promise<FilePermissionStatus>Check the current permission status for file operations. On Android, this checks for external storage permissions. On iOS and web, this always returns 'granted' as no special permissions are needed.
Returns: Promise<FilePermissionStatus>
requestPermissions(...)
requestPermissions(options?: PermissionRequestOptions | undefined) => Promise<FilePermissionStatus>Request permissions for file operations. On Android, this requests external storage permissions needed for accessing files outside the app's private directories. On iOS and web, this always returns 'granted' as no special permissions are needed.
| Param | Type | Description |
| ------------- | ----------------------------------------------------------------------------- | --------------------------------------------------- |
| options | PermissionRequestOptions | - Optional configuration for the permission request |
Returns: Promise<FilePermissionStatus>
Interfaces
FileSystem
Represents a file system
| Prop | Type | Description |
| ---------- | --------------------------------------------------------- | ------------------------------------- |
| name | string | The name of the file system |
| root | DirectoryEntry | The root directory of the file system |
DirectoryEntry
Represents a directory entry
| Prop | Type | Description |
| ----------------- | ------------------ | --------------------------- |
| isFile | false | True if this is a file |
| isDirectory | true | True if this is a directory |
RequestFileSystemOptions
Options for requesting a file system
| Prop | Type | Description |
| ---------- | --------------------------------------------------------- | -------------------------------------------------------------- |
| type | FileSystemType | The type of file system to request |
| size | number | Requested size in bytes (may not be enforced on all platforms) |
Entry
Represents a file or directory entry
| Prop | Type | Description |
| ----------------- | -------------------- | --------------------------------------------- |
| isFile | boolean | True if this is a file |
| isDirectory | boolean | True if this is a directory |
| name | string | The name of the file or directory |
| fullPath | string | The full path relative to the filesystem root |
| nativeURL | string | The native file:// URI |
ResolveURLOptions
Options for resolving a URL to an entry
| Prop | Type | Description |
| --------- | ------------------- | ------------------------------------------ |
| url | string | The URL to resolve (file:// or cdvfile://) |
FileEntry
Represents a file entry
| Prop | Type | Description |
| ----------------- | ------------------ | --------------------------- |
| isFile | true | True if this is a file |
| isDirectory | false | True if this is a directory |
GetFileOptions
Options for getting a file
| Prop | Type | Description |
| --------------- | ------------------------------------------------- | ----------------------------- |
| path | string | Path to the file |
| directory | Directory | Base directory |
| options | GetOptions | Options for creating the file |
GetOptions
Options for creating or getting files/directories
| Prop | Type | Description |
| --------------- | -------------------- | ------------------------------------------------------------------------ |
| create | boolean | Create the file/directory if it doesn't exist |
| exclusive | boolean | If true and create is true, throw error if file/directory already exists |
GetDirectoryOptions
Options for getting a directory
| Prop | Type | Description |
| --------------- | ------------------------------------------------- | ---------------------------------- |
| path | string | Path to the directory |
| directory | Directory | Base directory |
| options | GetOptions | Options for creating the directory |
ReadFileResult
Result of reading a file
| Prop | Type | Description |
| ---------- | ------------------- | ------------------------------------------------- |
| data | string | File contents as string (text) or base64 (binary) |
ReadFileOptions
Options for reading a file
| Prop | Type | Description |
| --------------- | ----------------------------------------------- | ------------------------------------------------------------------------ |
| path | string | Path to the file |
| directory | Directory | Base directory |
| encoding | Encoding | Encoding for text files (omit for binary/base64) |
| offset | number | Byte offset to start reading from (default: 0) |
| length | number | Number of bytes to read (default: read to end of file) |
WriteFileResult
Result of writing a file
| Prop | Type | Description |
| --------- | ------------------- | --------------------------- |
| uri | string | The URI of the written file |
WriteFileOptions
Options for writing a file
| Prop | Type | Description |
| --------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| path | string | Path to the file |
| directory | Directory | Base directory |
| data | string | Data to write (string for text, base64 for binary) |
| encoding | Encoding | Encoding for text files |
| append | boolean | If true, append to existing file instead of overwriting |
| recursive | boolean | Create intermediate directories if they don't exist |
| position | number | Byte position to start writing at (for random access writes). If not specified, writes from beginning or appends based on 'append' flag |
DeleteFileOptions
Options for deleting a file or directory
| Prop | Type | Description |
| --------------- | ----------------------------------------------- | ----------------------------- |
| path | string | Path to the file or directory |
| directory | Directory | Base directory |
MkdirOptions
Options for creating a directory
| Prop | Type | Description |
| --------------- | ----------------------------------------------- | --------------------------------------------------- |
| path | string | Path to the directory |
| directory | Directory | Base directory |
| recursive | boolean | Create intermediate directories if they don't exist |
DeleteDirectoryOptions
Options for deleting a directory recursively
| Prop | Type | Description |
| --------------- | ----------------------------------------------- | ------------------------------------ |
| path | string | Path to the directory |
| directory | Directory | Base directory |
| recursive | boolean | If true, delete contents recursively |
ReaddirResult
Result of reading a directory
| Prop | Type | Description |
| ------------- | -------------------- | -------------------------------- |
| entries | Entry[] | List of entries in the directory |
ReaddirOptions
Options for reading a directory
| Prop | Type | Description |
| --------------- | ----------------------------------------------- | --------------------- |
| path | string | Path to the directory |
| directory | Directory | Base directory |
StatResult
Result of getting file/directory information
| Prop | Type | Description |
| ----------- | ---------------------------------- | ---------------------------- |
| type | 'file' | 'directory' | Type: 'file' or 'directory' |
| size | number | Size in bytes |
| ctime | number | Creation time (if available) |
| mtime | number | Last modification time |
| uri | string | The URI |
StatOptions
Options for getting file information
| Prop | Type | Description |
| --------------- | ----------------------------------------------- | ----------------------------- |
| path | string | Path to the file or directory |
| directory | Directory | Base directory |
Metadata
Represents metadata about a file or directory
| Prop | Type | Description |
| ---------------------- | ------------------- | --------------------------------- |
| modificationTime | number | Last modification date |
| size | number | Size in bytes (0 for directories) |
RenameOptions
Options for renaming/moving a file or directory
| Prop | Type | Description |
| ----------------- | ----------------------------------------------- | ------------------------------ |
| from | string | Current path |
| to | string | New path |
| directory | Directory | Base directory for 'from' path |
| toDirectory | Directory | Base directory for 'to' path |
CopyResult
Result of copy operation
| Prop | Type | Description |
| --------- | ------------------- | -------------------------- |
| uri | string | The URI of the copied file |
CopyOptions
Options for copying a file or directory
| Prop | Type | Description |
| ----------------- | ----------------------------------------------- | ------------------------------ |
| from | string | Source path |
| to | string | Destination path |
| directory | Directory | Base directory for source |
| toDirectory | Directory | Base directory for destination |
ExistsResult
Result of existence check
| Prop | Type | Description |
| ------------ | ---------------------------------- | ------------------------------------- |
| exists | boolean | True if the file or directory exists |
| type | 'file' | 'directory' | Type if exists: 'file' or 'directory' |
ExistsOptions
Options for checking if a file or directory exists
| Prop | Type | Description |
| --------------- | ----------------------------------------------- | -------------- |
| path | string | Path to check |
| directory | Directory | Base directory |
GetUriResult
Result of getting a URI
| Prop | Type | Description |
| --------- | ------------------- | -------------- |
| uri | string | The native URI |
GetUriOptions
Options for getting the URI of a file
| Prop | Type | Description |
| --------------- | ----------------------------------------------- | ---------------- |
| path | string | Path to the file |
| directory | Directory | Base directory |
TruncateOptions
Options for truncating a file
| Prop | Type | Description |
| --------------- | ----------------------------------------------- | -------------------------------- |
| path | string | Path to the file |
| directory | Directory | Base directory |
| size | number | Size to truncate to (default: 0) |
FileDirectories
Known file system directories exposed by the plugin
| Prop | Type | Description |
| ----------------------------------------- | ------------------- | ------------------------------------------------ |
| applicationDirectory | string | Application installation directory (read-only) |
| applicationStorageDirectory | string | Application storage directory root |
| dataDirectory | string | Persistent private data directory |
| cacheDirectory | string | Cache directory |
| externalRootDirectory | string | External root directory (Android) |
| externalApplicationStorageDirectory | string | External application storage directory (Android) |
| externalDataDirectory | string | External data directory (Android) |
| externalCacheDirectory | string | External cache directory (Android) |
| documentsDirectory | string | Documents directory (iOS) |
| syncedDataDirectory | string | Synced data directory (iOS iCloud) |
| libraryDirectory | string | Library directory (iOS) |
| tempDirectory | string | Temporary directory |
PluginListenerHandle
| Prop | Type |
| ------------ | ----------------------------------------- |
| remove | () => Promise<void> |
ProgressEvent
Progress event for file operations
| Prop | Type | Description |
| ---------------------- | -------------------- | --------------------------- |
| loaded | number | Bytes loaded so far |
| total | number | Total bytes (if known) |
| lengthComputable | boolean | Whether total is computable |
FilePermissionStatus
Permission status for file operations
| Prop | Type | Description |
| ------------------- | ----------------------------------------------------------- | ---------------------------------------------------- |
| publicStorage | PermissionState | Permission state for reading public/external storage |
PermissionRequestOptions
Options for requesting permissions
| Prop | Type | Description | Default |
| ----------------------------- | -------------------- | ------------------------------------------------------------------ | ------------------ |
| showSettingsAlert | boolean | If true, shows an alert to open settings when permission is denied | false |
| title | string | Title for the settings alert dialog | |
| message | string | Message for the settings alert dialog | |
| openSettingsButtonTitle | string | Text for the "Open Settings" button | |
| cancelButtonTitle | string | Text for the "Cancel" button | |
Type Aliases
PermissionState
'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'
Enums
FileSystemType
| Members | Value |
| ---------------- | -------------- |
| TEMPORARY | 0 |
| PERSISTENT | 1 |
Directory
| Members | Value | Description |
| --------------------- | ------------------------------- | --------------------------------------------------------------------------------------------- |
| Documents | 'DOCUMENTS' | The Documents directory (iOS) / files directory (Android) Persistent, user-visible, backed up |
| Data | 'DATA' | The Data directory Persistent private data storage |
| Library | 'LIBRARY' | The Library directory (iOS) / files directory (Android) Persistent but not visible to user |
| Cache | 'CACHE' | The Cache directory Temporary cache, may be cleared by OS |
| External | 'EXTERNAL' | External storage (Android only) SD card or external storage root |
| ExternalStorage | 'EXTERNAL_STORAGE' | External storage data directory (Android only) |
| Application | 'APPLICATION' | Application bundle/assets directory (read-only) |
Encoding
| Members | Value |
| ----------- | -------------------- |
| UTF8 | 'utf8' |
| ASCII | 'ascii' |
| UTF16 | 'utf16' |
Usage Examples
Reading a File
import { CapacitorFile, Directory, Encoding } from '@capgo/capacitor-file';
// Read as text
const result = await CapacitorFile.readFile({
path: 'my-file.txt',
directory: Directory.Documents,
encoding: Encoding.UTF8,
});
console.log(result.data);
// Read as base64 (binary)
const binaryResult = await CapacitorFile.readFile({
path: 'image.png',
directory: Directory.Documents,
});
console.log(binaryResult.data); // base64 string
// Read partial file (offset and length) - great for large files!
const partialResult = await CapacitorFile.readFile({
path: 'large-file.bin',
directory: Directory.Documents,
offset: 1024, // Start at byte 1024
length: 512, // Read 512 bytes
});
console.log(partialResult.data); // base64 encoded chunkWriting a File
import { CapacitorFile, Directory, Encoding } from '@capgo/capacitor-file';
// Write text
await CapacitorFile.writeFile({
path: 'my-file.txt',
directory: Directory.Documents,
data: 'Hello, World!',
encoding: Encoding.UTF8,
recursive: true, // Create parent directories if needed
});
// Write binary (base64)
await CapacitorFile.writeFile({
path: 'image.png',
directory: Directory.Documents,
data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
});
// Write at specific position (random access) - great for patching files!
await CapacitorFile.writeFile({
path: 'data.bin',
directory: Directory.Documents,
data: 'PATCHED',
encoding: Encoding.UTF8,
position: 100, // Write starting at byte 100
});Creating and Reading Directories
import { CapacitorFile, Directory } from '@capgo/capacitor-file';
// Create a directory
await CapacitorFile.mkdir({
path: 'my-folder/sub-folder',
directory: Directory.Documents,
recursive: true,
});
// Read directory contents
const result = await CapacitorFile.readdir({
path: 'my-folder',
directory: Directory.Documents,
});
for (const entry of result.entries) {
console.log(`${entry.name} - ${entry.isFile ? 'file' : 'directory'}`);
}Copying and Moving Files
import { CapacitorFile, Directory } from '@capgo/capacitor-file';
// Copy a file
await CapacitorFile.copy({
from: 'original.txt',
to: 'backup/original-copy.txt',
directory: Directory.Documents,
toDirectory: Directory.Documents,
});
// Move/rename a file
await CapacitorFile.rename({
from: 'old-name.txt',
to: 'new-name.txt',
directory: Directory.Documents,
});Checking File Existence
import { CapacitorFile, Directory } from '@capgo/capacitor-file';
const result = await CapacitorFile.exists({
path: 'my-file.txt',
directory: Directory.Documents,
});
if (result.exists) {
console.log(`Found ${result.type}`);
}Getting File Information
import { CapacitorFile, Directory } from '@capgo/capacitor-file';
const stat = await CapacitorFile.stat({
path: 'my-file.txt',
directory: Directory.Documents,
});
console.log(`Size: ${stat.size} bytes`);
console.log(`Modified: ${new Date(stat.mtime)}`);
console.log(`Type: ${stat.type}`);Migration from cordova-plugin-file
This plugin provides similar functionality to cordova-plugin-file with a more modern API. Here's a quick comparison:
| Cordova File Plugin | This Plugin |
|---------------------|-------------|
| window.resolveLocalFileSystemURL() | CapacitorFile.resolveLocalFileSystemURL() |
| directoryEntry.getFile() | CapacitorFile.getFile() |
| directoryEntry.getDirectory() | CapacitorFile.getDirectory() |
| fileReader.readAsText() | CapacitorFile.readFile({ encoding: Encoding.UTF8 }) |
| fileReader.readAsDataURL() | CapacitorFile.readAsDataURL() |
| fileWriter.write() | CapacitorFile.writeFile() |
| entry.remove() | CapacitorFile.deleteFile() |
| entry.moveTo() | CapacitorFile.move() |
| entry.copyTo() | CapacitorFile.copy() |
| directoryEntry.removeRecursively() | CapacitorFile.rmdir({ recursive: true }) |
| cordova.file.dataDirectory | Directory.Data |
| cordova.file.documentsDirectory | Directory.Documents |
| cordova.file.cacheDirectory | Directory.Cache |
License
MPL-2.0
