### Build and Run Example App Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/example-app/README.md Navigate to the example-app directory and run these commands to build and start the web application. ```bash cd example-app npm install & npm run build npm start ``` -------------------------------- ### Build Plugin and Install Dependencies Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/example-app/README.md Run these commands in the project root to install dependencies and build the plugin. ```bash npm install & npm run build ``` -------------------------------- ### Install Dependencies Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/CONTRIBUTING.md Run this command after forking and cloning the repository to install project dependencies. ```shell npm install ``` -------------------------------- ### Install Capacitor Filesystem Plugin Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Install the plugin using npm and sync native projects with the Capacitor CLI. ```bash npm install @capacitor/filesystem npx cap sync ``` -------------------------------- ### User Settings Service Example with Capacitor Filesystem Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt This example demonstrates a complete user settings service using Capacitor Filesystem. It covers initializing directories, saving, loading, and retrieving metadata for a user settings JSON file. It handles potential errors like the directory already existing or the file not being found on the first run. ```typescript import { Filesystem, Directory, Encoding } from '@capacitor/filesystem'; const SETTINGS_DIR = 'config'; const SETTINGS_FILE = 'config/user-settings.json'; const DIR = Directory.Data; interface UserSettings { theme: 'light' | 'dark'; language: string; notifications: boolean; lastSync: string; } const defaultSettings: UserSettings = { theme: 'light', language: 'en', notifications: true, lastSync: new Date().toISOString(), }; async function initSettingsDir(): Promise { try { await Filesystem.mkdir({ path: SETTINGS_DIR, directory: DIR, recursive: true }); } catch (err: any) { if (err.code !== 'OS-PLUG-FILE-0010') throw err; // ignore "already exists" } } async function saveSettings(settings: UserSettings): Promise { await initSettingsDir(); await Filesystem.writeFile({ path: SETTINGS_FILE, data: JSON.stringify(settings, null, 2), directory: DIR, encoding: Encoding.UTF8, }); } async function loadSettings(): Promise { try { const { data } = await Filesystem.readFile({ path: SETTINGS_FILE, directory: DIR, encoding: Encoding.UTF8, }); return JSON.parse(data as string) as UserSettings; } catch (err: any) { if (err.code === 'OS-PLUG-FILE-0008') { // First run — write defaults await saveSettings(defaultSettings); return defaultSettings; } throw err; } } async function getSettingsMetadata(): Promise { const info = await Filesystem.stat({ path: SETTINGS_FILE, directory: DIR }); console.log(`Settings file: ${info.size} bytes, last modified ${new Date(info.mtime).toISOString()}`); } // Usage (async () => { const settings = await loadSettings(); console.log('Loaded settings:', settings); settings.theme = 'dark'; settings.lastSync = new Date().toISOString(); await saveSettings(settings); await getSettingsMetadata(); // => Settings file: 112 bytes, last modified 2024-01-15T10:30:00.000Z })(); ``` -------------------------------- ### Install SwiftLint (macOS) Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/CONTRIBUTING.md If you are on macOS, install SwiftLint using Homebrew to adhere to Swift code style guidelines. ```shell brew install swiftlint ``` -------------------------------- ### Migrate from Filesystem downloadFile to File Transfer Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Example demonstrating the migration from using Filesystem.downloadFile to the new FileTransfer.downloadFile method. Note the initial use of Filesystem.getUri to obtain the file path for FileTransfer. ```typescript import { Filesystem, Directory } from '@capacitor/filesystem'; await Filesystem.downloadFile({ url: 'https://example.com/file.pdf', path: 'downloaded-file.pdf', directory: Directory.Documents, progress: true }); // Progress events Filesystem.addListener('progress', (progress) => { console.log(`Downloaded ${progress.bytes} of ${progress.contentLength}`); }); ``` ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; // First get the full file path using Filesystem const fileInfo = await Filesystem.getUri({ directory: Directory.Documents, path: 'downloaded-file.pdf' }); // Then use the FileTransfer plugin to download await FileTransfer.downloadFile({ url: 'https://example.com/file.pdf', path: fileInfo.uri, progress: true }); // Progress events FileTransfer.addListener('progress', (progress) => { console.log(`Downloaded ${progress.bytes} of ${progress.contentLength}`); }); ``` -------------------------------- ### Install Capacitor File Transfer Plugin Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Install the File Transfer plugin, which replaces the deprecated downloadFile functionality from the Filesystem plugin. ```bash npm install @capacitor/file-transfer npx cap sync ``` -------------------------------- ### Android Storage Permissions Setup Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt For `Directory.Documents` or `Directory.ExternalStorage` on Android 10 and older, add `READ_EXTERNAL_STORAGE` and `WRITE_EXTERNAL_STORAGE` permissions to `AndroidManifest.xml`. ```xml ``` -------------------------------- ### Example PrivacyInfo.xcprivacy for File Timestamp Access Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md This XML configuration is required for Apple privacy manifest requirements when accessing file timestamps. It should be placed in `/ios/App/PrivacyInfo.xcprivacy`. ```xml NSPrivacyAccessedAPITypes NSPrivacyAccessedAPIType NSPrivacyAccessedAPICategoryFileTimestamp NSPrivacyAccessedAPITypeReasons C617.1 ``` -------------------------------- ### Get File/Directory Metadata with Capacitor Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Returns metadata about a file or directory, including name, type, size, creation time, modification time, and native URI. Handles 'file not found' errors. ```typescript import { Filesystem, Directory } from '@capacitor/filesystem'; async function inspectFile(): Promise { try { const info = await Filesystem.stat({ path: 'user-data/profile.json', directory: Directory.Data, }); console.log('Name:', info.name); console.log('Type:', info.type); // 'file' | 'directory' console.log('Size:', info.size, 'bytes'); console.log('Created:', new Date(info.ctime ?? 0).toISOString()); console.log('Modified:', new Date(info.mtime).toISOString()); console.log('URI:', info.uri); } catch (err: any) { if (err.code === 'OS-PLUG-FILE-0008') { console.warn('File does not exist'); } } } ``` -------------------------------- ### Get Native File URI with Capacitor Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Resolves the full native `file://` URI for a logical path and directory. Useful for passing file paths to other plugins. ```typescript import { Filesystem, Directory } from '@capacitor/filesystem'; async function getNativeUri(): Promise { const { uri } = await Filesystem.getUri({ path: 'exports/data.json', directory: Directory.Documents, }); console.log('Native URI:', uri); // iOS example: "file:///var/mobile/Containers/Data/Application/.../Documents/exports/data.json" // Android example: "file:///data/user/0/com.example/files/exports/data.json" // Pass the URI to another plugin, e.g. FileTransfer // await FileTransfer.uploadFile({ path: uri, url: 'https://api.example.com/upload' }); } ``` -------------------------------- ### getUri(...) Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Gets the URI for a file or directory. This is useful for sharing files with other applications or plugins. ```APIDOC ## getUri(...) ### Description Get the URI for a file or directory ### Method getUri(options: GetUriOptions) ### Parameters #### Request Body - **`options`** (`GetUriOptions`) - Required - Options for getting the URI. ### Returns `Promise` ### Since 1.0.0 ``` -------------------------------- ### mkdir Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Create a directory. Accepts a MkdirOptions object and returns a Promise. ```APIDOC ## mkdir(...) ### Description Create a directory. ### Method ```typescript mkdir(options: MkdirOptions) => Promise ``` ### Parameters #### Request Body - **options** (MkdirOptions) - Required - Options for creating the directory. ``` -------------------------------- ### mkdir Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Creates a new directory. Set `recursive: true` to create all missing parent directories. Throws `OS-PLUG-FILE-0010` if the directory already exists. ```APIDOC ## mkdir(options) ### Description Creates a new directory. Set `recursive: true` to create all missing parent directories. Throws `OS-PLUG-FILE-0010` if the directory already exists. ### Method ```typescript Filesystem.mkdir ``` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the directory to create. - **directory** (Directory) - Required - The base directory to create the new directory in. Possible values are `Directory.Documents`, `Directory.Data`, `Directory.Cache`, `Directory.External`, `Directory.ExternalCache`, `Directory.Local`. - **recursive** (boolean) - Optional - If true, all missing parent directories will be created. Defaults to `false`. ### Request Example ```typescript await Filesystem.mkdir({ path: "app-data/users/profile/avatars", directory: Directory.Data, recursive: true }); ``` ### Response No specific response data is returned on success. ``` -------------------------------- ### Sync and Run Mobile App Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/example-app/README.md Execute these commands to synchronize Capacitor with the native projects and run the mobile application. ```bash npx cap sync npx cap run ``` -------------------------------- ### MkdirOptions Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Options for creating a new directory. ```APIDOC ## MkdirOptions ### Description Options for creating a new directory. ### Parameters #### Path Parameters - **`path`** (string) - Required - The path of the new directory. - **`directory`** (Directory) - Required - The `Directory` to make the new directory in. - **`recursive`** (boolean) - Optional - Whether to create any missing parent directories as well. Defaults to `false`. ``` -------------------------------- ### mkdir(...) Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Creates a directory on the disk. You can specify the path and the directory where the new directory should be created. ```APIDOC ## mkdir(...) ### Description Create a directory on disk ### Method mkdir(options: MkdirOptions) ### Parameters #### Request Body - **`options`** (`MkdirOptions`) - Required - Options for creating the directory. ### Since 1.0.0 ``` -------------------------------- ### Write Text and Binary Files with Capacitor Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Demonstrates writing UTF-8 text and base64-encoded binary data to files. Use `recursive: true` to create parent directories if they don't exist. Binary data should not have an encoding specified. ```typescript import { Filesystem, Directory, Encoding } from '@capacitor/filesystem'; async function writeExamples(): Promise { // --- Write a UTF-8 text file, auto-creating parent directories --- const result = await Filesystem.writeFile({ path: 'notes/daily/2024-01-15.txt', data: 'Meeting at 10am\nLunch at noon', directory: Directory.Documents, encoding: Encoding.UTF8, recursive: true, // creates notes/daily/ if it doesn't exist }); console.log('Written to:', result.uri); // => "file:///var/mobile/.../Documents/notes/daily/2024-01-15.txt" // --- Write binary data (base64-encoded PNG) --- const base64Image = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='; await Filesystem.writeFile({ path: 'images/thumbnail.png', data: base64Image, // no encoding = binary write directory: Directory.Cache, recursive: true, }); // --- Write a Blob (web only) --- const blob = new Blob(['Hello, Blob!'], { type: 'text/plain' }); await Filesystem.writeFile({ path: 'blob-file.txt', data: blob, directory: Directory.Data, }); } ``` -------------------------------- ### Create Directories with Capacitor Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Creates new directories. Set `recursive: true` to create all missing parent directories. Throws an error if the directory already exists and `recursive` is false. ```typescript import { Filesystem, Directory } from '@capacitor/filesystem'; async function setupDirectoryStructure(): Promise { // Create a nested structure in one call await Filesystem.mkdir({ path: 'app-data/users/profile/avatars', directory: Directory.Data, recursive: true, }); // Create a single directory (parent must exist) try { await Filesystem.mkdir({ path: 'reports', directory: Directory.Documents, recursive: false, }); } catch (err: any) { if (err.code === 'OS-PLUG-FILE-0010') { console.log('Directory already exists, continuing…'); } else { throw err; } } } ``` -------------------------------- ### Build Plugin and API Docs Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/CONTRIBUTING.md This script builds the plugin's web assets and generates API documentation. It compiles TypeScript to ESM JavaScript and bundles it into a single file for use in applications. ```shell npm run build ``` -------------------------------- ### Copy Files and Directories with Capacitor Filesystem Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt The `copy` method duplicates files or directories to a new location, preserving the source. It returns the URI of the new copy. Supports copying across directories and entire directory trees. ```typescript import { Filesystem, Directory } from '@capacitor/filesystem'; async function backupUserData(): Promise { // Copy a single file const { uri } = await Filesystem.copy({ from: 'database/app.db', to: 'backups/app-backup.db', directory: Directory.Data, }); console.log('Backup written to:', uri); // Copy across directories: Cache → Documents await Filesystem.copy({ from: 'temp/generated-report.pdf', to: 'reports/generated-report.pdf', directory: Directory.Cache, toDirectory: Directory.Documents, }); // Copy an entire directory tree await Filesystem.copy({ from: 'session-data', to: 'session-backup', directory: Directory.Data, }); } ``` -------------------------------- ### Build and Validate Projects Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/CONTRIBUTING.md Use this script to build and validate both the web and native projects. This is essential for CI to ensure the plugin builds correctly across all platforms. ```shell npm run verify ``` -------------------------------- ### Write, Read, and Delete Files with Capacitor Filesystem Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Demonstrates basic file operations: writing data to a file in the Documents directory, reading it back, and then deleting it. Ensure the necessary permissions are handled before performing these operations on Android. ```typescript import { Filesystem, Directory, Encoding } from "@capacitor/filesystem"; const writeSecretFile = async () => { await Filesystem.writeFile({ path: "secrets/text.txt", data: "This is a test", directory: Directory.Documents, encoding: Encoding.UTF8, }); }; const readSecretFile = async () => { const contents = await Filesystem.readFile({ path: "secrets/text.txt", directory: Directory.Documents, encoding: Encoding.UTF8, }); console.log("secrets:", contents); }; const deleteSecretFile = async () => { await Filesystem.deleteFile({ path: "secrets/text.txt", directory: Directory.Documents, }); }; ``` ```typescript const readFilePath = async () => { // Here's an example of reading a file with a full file path. Use this to // read binary data (base64 encoded) from plugins that return File URIs, such as // the Camera. const contents = await Filesystem.readFile({ path: "file:///var/mobile/Containers/Data/Application/22A433FD-D82D-4989-8BE6-9FC49DEA20BB/Documents/text.txt", }); console.log("data:", contents); }; ``` ```typescript const appendBinaryData = async () => { // Here's an example of appending binary data, which should be sent to the plugin // as base64 encoded, and without providing any `Encoding`. await Filesystem.appendFile({ path: "file.bin", directory: Directory.Cache, data: "VGhpcyBpcyBtZWFudCB0byByZXByZXNlbnQgYSBCaW5hcnkgRGF0YSBleGFtcGxlIGVuY29kZWQgaW4gQmFzZTY0Lg==" }); }; ``` -------------------------------- ### copy(options) Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Copies a file or directory to a new location. The source is preserved. Returns the URI of the new copy. ```APIDOC ## copy(options) ### Description Copies a file or directory to a new location. The source is preserved. Returns the URI of the new copy. ### Method ```typescript await Filesystem.copy({ from: string, to: string, directory?: Directory, toDirectory?: Directory }); ``` ### Parameters #### Path Parameters - **from** (string) - Required - The path of the file or directory to copy. - **to** (string) - Required - The destination path for the copied file or directory. - **directory** (Directory) - Optional - The directory where the `from` path resides. Defaults to `Directory.Documents`. - **toDirectory** (Directory) - Optional - The directory where the `to` path should be created. Defaults to the same directory as `directory`. ### Response #### Success Response (200) - **uri** (string) - The URI of the newly created copy. ### Request Example ```typescript // Copy a single file const { uri } = await Filesystem.copy({ from: 'database/app.db', to: 'backups/app-backup.db', directory: Directory.Data, }); console.log('Backup written to:', uri); // Copy across directories: Cache → Documents await Filesystem.copy({ from: 'temp/generated-report.pdf', to: 'reports/generated-report.pdf', directory: Directory.Cache, toDirectory: Directory.Documents, }); // Copy an entire directory tree await Filesystem.copy({ from: 'session-data', to: 'session-backup', directory: Directory.Data, }); ``` ``` -------------------------------- ### Lint and Format Code Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/CONTRIBUTING.md Run these commands to check code quality and formatting. `fmt` can autoformat/autofix issues. The `lint` command is used in CI. ```shell npm run lint ``` ```shell npm run fmt ``` -------------------------------- ### addListener('progress', ...) Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Adds a listener for the 'progress' event, which is triggered during file download operations to report progress. ```APIDOC ## addListener('progress', ...) ### Description Listen for 'progress' events during file downloads. ### Method addListener('progress', callback: (event: ProgressEvent) => void) ### Parameters #### Request Body - **`callback`** - Required - Function to call when progress updates. ### Returns `Promise` ### Since 1.0.0 ``` -------------------------------- ### writeFile Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Write a file to disk in the specified location on device. Accepts a WriteFileOptions object and returns a Promise resolving to a WriteFileResult. ```APIDOC ## writeFile(...) ### Description Write a file to disk in the specified location on device. ### Method ```typescript writeFile(options: WriteFileOptions) => Promise ``` ### Parameters #### Request Body - **options** (WriteFileOptions) - Required - Options for writing the file. ``` -------------------------------- ### DownloadFileOptions Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Options for the downloadFile method. ```APIDOC ## DownloadFileOptions ### Description Options to configure the file download. ### Properties - **`path`** (string) - The path the downloaded file should be moved to. - **`directory`** (Directory) - The directory to write the file to. If this option is used, filePath can be a relative path rather than absolute. The default is the `DATA` directory. - **`progress`** (boolean) - An optional listener function to receive downloaded progress events. If this option is used, progress event should be dispatched on every chunk received. Chunks are throttled to every 100ms on Android/iOS to avoid slowdowns. - **`recursive`** (boolean) - Whether to create any missing parent directories. Defaults to `false`. ``` -------------------------------- ### ProgressStatus Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Represents the progress status of a download. ```APIDOC ## ProgressStatus ### Description Information about the current download progress. ### Properties - **`url`** (string) - The url of the file being downloaded. - **`bytes`** (number) - The number of bytes downloaded so far. - **`contentLength`** (number) - The total number of bytes to download for this file. ``` -------------------------------- ### GetUriOptions Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Options for the getUri operation. ```APIDOC ## GetUriOptions ### Description Options that can be provided to the getUri operation. ### Properties - **`path`** (string) - The path of the file to get the URI for. - **`directory`** (Directory) - The `Directory` to get the file under. ``` -------------------------------- ### CopyOptions Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Options for the copy operation. ```APIDOC ## CopyOptions ### Description Options that can be provided to the copy operation. ### Properties - **`from`** (string) - The existing file or directory. - **`to`** (string) - The destination file or directory. - **`directory`** (Directory) - The `Directory` containing the existing file or directory. - **`toDirectory`** (Directory) - The `Directory` containing the destination file or directory. If not supplied will use the 'directory' parameter as the destination. ``` -------------------------------- ### writeFile Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Writes data to a file at the specified path and directory. Text data requires an Encoding; binary data must be base64-encoded and passed without an encoding. Set recursive: true to auto-create missing parent directories. Returns the native URI of the written file. ```APIDOC ## writeFile(options) ### Description Writes data to a file at the specified path and directory. Text data requires an `Encoding`; binary data must be base64-encoded and passed without an encoding. Set `recursive: true` to auto-create missing parent directories. Returns the native URI of the written file. ### Parameters #### Path Parameters - **path** (string) - Required - The path to the file within the specified directory. - **data** (string | Blob) - Required - The data to write to the file. For text, use a string with an encoding. For binary, use a base64-encoded string or a Blob. - **directory** (Directory) - Required - The target directory (e.g., `Directory.Documents`, `Directory.Cache`). - **encoding** (Encoding) - Optional - The encoding for text data (e.g., `Encoding.UTF8`). Omit for binary data. - **recursive** (boolean) - Optional - If true, creates missing parent directories automatically. ### Request Example ```typescript await Filesystem.writeFile({ path: 'notes/daily/2024-01-15.txt', data: 'Meeting at 10am\nLunch at noon', directory: Directory.Documents, encoding: Encoding.UTF8, recursive: true, }); ``` ### Response #### Success Response (200) - **uri** (string) - The native URI of the written file. ``` -------------------------------- ### WriteFileOptions Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Options for writing a file. ```APIDOC ## WriteFileOptions ### Description Options for writing a file. ### Parameters #### Path Parameters - **path** (string) - Required - The path of the file to write - **data** (string | Blob) - Required - The data to write. Note: Blob data is only supported on Web. - **directory** (Directory) - Required - The `Directory` to store the file in - **encoding** (Encoding) - Optional - The encoding to write the file in. If not provided, binary data will be written. For this, you must provide data as base64 encoded, so that the plugin can decode it before writing to disk. If you do not provide encoding and use non-base64 data, an error will be thrown. Pass Encoding.UTF8 to write data as string - **recursive** (boolean) - Optional - Whether to create any missing parent directories. Defaults to `false`. ``` -------------------------------- ### Download File with Capacitor Filesystem Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Use this method to perform an HTTP request and download a file to a specified destination. Note: This method is deprecated and the @capacitor/file-transfer plugin is recommended. ```typescript downloadFile(options: DownloadFileOptions) => Promise ``` -------------------------------- ### Handle Capacitor Filesystem Errors by Code Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Since v7.1.0, the plugin throws structured errors with a `code` field. Catching by code enables fine-grained recovery logic for specific issues like invalid parameters, paths, or permissions. ```typescript import { Filesystem, Directory, Encoding } from '@capacitor/filesystem'; import type { PluginError } from '@capacitor/filesystem'; async function robustFileRead(path: string): Promise { try { const { data } = await Filesystem.readFile({ path, directory: Directory.Data, encoding: Encoding.UTF8, }); return data as string; } catch (err: any) { const code: string = (err as PluginError).code ?? ''; switch (code) { case 'OS-PLUG-FILE-0005': console.error('Invalid parameters provided'); break; case 'OS-PLUG-FILE-0006': console.error('Invalid path:', path); break; case 'OS-PLUG-FILE-0007': console.error('Permission denied — request permissions first'); break; case 'OS-PLUG-FILE-0008': console.warn('File not found:', path); break; case 'OS-PLUG-FILE-0013': console.error('Unknown OS-level error'); break; default: console.error('Unexpected error:', err); } return null; } } // OS-PLUG-FILE-0004 iOS Bridge not initialized // OS-PLUG-FILE-0005 Both Invalid input parameters // OS-PLUG-FILE-0006 Both Invalid path // OS-PLUG-FILE-0007 Android Permission denied // OS-PLUG-FILE-0008 Both File/directory does not exist // OS-PLUG-FILE-0009 Android Operation not supported for input // OS-PLUG-FILE-0010 Both Directory already exists // OS-PLUG-FILE-0011 Both Missing parent directory // OS-PLUG-FILE-0012 Both Directory not empty (recursive=false) // OS-PLUG-FILE-0013 Both Generic OS failure ``` -------------------------------- ### PluginListenerHandle Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Handle for a registered plugin listener. ```APIDOC ## PluginListenerHandle ### Description Provides a way to remove a listener. ### Properties - **`remove`** (() => Promise) - A function that removes the listener. ``` -------------------------------- ### addListener('progress', ...) Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Adds a listener to receive file download progress events. This method is deprecated and recommends using the @capacitor/file-transfer plugin. ```APIDOC ## addListener('progress', ...) ### Description Add a listener to file download progress events. This method has been deprecated since version 7.1.0. We recommend using the @capacitor/file-transfer plugin instead, in conjunction with this plugin. ### Parameters #### Path Parameters - **`eventName`** ('progress') - Required - The name of the event to listen for. - **`listenerFunc`** (ProgressListener) - Required - The function to call when the progress event is fired. ### Returns - **Promise** - A promise that resolves with a handle to the listener. ### Since 5.1.0 ``` -------------------------------- ### appendFile Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Append to a file on disk in the specified location on device. Accepts an AppendFileOptions object and returns a Promise. ```APIDOC ## appendFile(...) ### Description Append to a file on disk in the specified location on device. ### Method ```typescript appendFile(options: AppendFileOptions) => Promise ``` ### Parameters #### Request Body - **options** (AppendFileOptions) - Required - Options for appending to the file. ``` -------------------------------- ### copy Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Copy a file or directory. Accepts a CopyOptions object and returns a Promise resolving to a CopyResult. ```APIDOC ## copy(...) ### Description Copy a file or directory. ### Method ```typescript copy(options: CopyOptions) => Promise ``` ### Parameters #### Request Body - **options** (CopyOptions) - Required - Options for copying the file or directory. ``` -------------------------------- ### AppendFileOptions Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Options for appending data to a file. If encoding is not provided, binary data must be base64 encoded. ```APIDOC ## AppendFileOptions ### Description Options for appending data to a file. If encoding is not provided, binary data must be base64 encoded. ### Parameters #### Path Parameters - **`path`** (string) - Required - The path of the file to append. - **`data`** (string) - Required - The data to append. - **`directory`** (Directory) - Required - The `Directory` to store the file in. - **`encoding`** (Encoding) - Optional - The encoding to append to the file. If not provided, binary data will be appended. For this, you must provide data as base64 encoded, so that the plugin can decode it before writing to disk. If you do not provide encoding and use non-base64 data, an error will be thrown. Pass `Encoding.UTF8` to write data as string. ``` -------------------------------- ### ReadFileOptions Interface Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Options for reading a file, including path, directory, encoding, offset, and length. Offset and length are native-only. ```typescript path: string directory: Directory encoding: Encoding offset: number length: number ``` -------------------------------- ### appendFile(...) Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Appends binary data to a file on disk. The data should be base64 encoded, and no encoding should be specified. ```APIDOC ## appendFile(...) ### Description Append binary data to a file on disk. ### Method appendFile(options: AppendFileOptions) ### Parameters #### Request Body - **`options`** (`AppendFileOptions`) - Required - Options for appending to the file. ### Since 1.0.0 ``` -------------------------------- ### stat Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Returns metadata about a file or directory: name, type (`'file'` or `'directory'`), size in bytes, creation time (`ctime`), modification time (`mtime`), and native URI. ```APIDOC ## stat(options) ### Description Returns metadata about a file or directory: name, type (`'file'` or `'directory'`), size in bytes, creation time (`ctime`), modification time (`mtime`), and native URI. ### Method ```typescript Filesystem.stat ``` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the file or directory. - **directory** (Directory) - Required - The base directory. Possible values are `Directory.Documents`, `Directory.Data`, `Directory.Cache`, `Directory.External`, `Directory.ExternalCache`, `Directory.Local`. ### Request Example ```typescript await Filesystem.stat({ path: 'user-data/profile.json', directory: Directory.Data }); ``` ### Response #### Success Response (200) - **name** (string) - The name of the file or directory. - **type** (string) - The type of the entry, either 'file' or 'directory'. - **size** (number) - The size of the file in bytes. For directories, this value is typically 0. - **uri** (string) - The native URI of the file or directory. - **ctime** (number) - The creation timestamp of the file or directory (milliseconds since epoch). - **mtime** (number) - The modification timestamp of the file or directory (milliseconds since epoch). ### Response Example ```json { "name": "profile.json", "type": "file", "size": 1024, "uri": "file:///path/to/your/app/Data/user-data/profile.json", "ctime": 1673740800000, "mtime": 1673740800000 } ``` ``` -------------------------------- ### copy(...) Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Copies a file or directory from one location to another. You need to specify the source and destination paths. ```APIDOC ## copy(...) ### Description Copy a file or directory ### Method copy(options: CopyOptions) ### Parameters #### Request Body - **`options`** (`CopyOptions`) - Required - Options for copying the file or directory. ### Since 1.0.0 ``` -------------------------------- ### PermissionState Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Represents the possible states of a permission. ```APIDOC ## PermissionState ### Description Possible states for file system permissions. ### Type `'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'` ``` -------------------------------- ### getUri Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Resolves the full native `file://` URI for a logical path and directory. Useful for passing file paths to other plugins (e.g., Camera, File Transfer, Media). ```APIDOC ## getUri(options) ### Description Resolves the full native `file://` URI for a logical path and directory. Useful for passing file paths to other plugins (e.g., Camera, File Transfer, Media). ### Method ```typescript Filesystem.getUri ``` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the file or directory. - **directory** (Directory) - Required - The base directory. Possible values are `Directory.Documents`, `Directory.Data`, `Directory.Cache`, `Directory.External`, `Directory.ExternalCache`, `Directory.Local`. ### Request Example ```typescript await Filesystem.getUri({ path: 'exports/data.json', directory: Directory.Documents }); ``` ### Response #### Success Response (200) - **uri** (string) - The native `file://` URI for the specified path and directory. ``` -------------------------------- ### getUri Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Return full File URI for a path and directory. Accepts a GetUriOptions object and returns a Promise resolving to a GetUriResult. ```APIDOC ## getUri(...) ### Description Return full File URI for a path and directory. ### Method ```typescript getUri(options: GetUriOptions) => Promise ``` ### Parameters #### Request Body - **options** (GetUriOptions) - Required - Options for getting the file URI. ``` -------------------------------- ### List Directory Contents with Capacitor Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Lists the contents of a directory (non-recursive). Returns an array of `FileInfo` objects with name, type, size, URI, and timestamps. Filters results to show subdirectories and files separately. ```typescript import { Filesystem, Directory } from '@capacitor/filesystem'; import type { FileInfo } from '@capacitor/filesystem'; async function listDirectory(): Promise { const { files } = await Filesystem.readdir({ path: 'documents', directory: Directory.Data, }); const subdirs = files.filter((f: FileInfo) => f.type === 'directory'); const fileEntries = files.filter((f: FileInfo) => f.type === 'file'); console.log(`Found ${subdirs.length} directories and ${fileEntries.length} files`); for (const f of fileEntries) { const modifiedDate = new Date(f.mtime).toLocaleDateString(); console.log(` ${f.name} — ${f.size} bytes — modified ${modifiedDate} — uri: ${f.uri}`); } // Example output: // report.pdf — 204800 bytes — modified 1/15/2024 — uri: file:///…/Data/documents/report.pdf } ``` -------------------------------- ### writeFile(...) Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Writes data to a file on disk. You can specify the path, data, directory, and encoding. If the file exists, it will be overwritten. ```APIDOC ## writeFile(...) ### Description Write a file to disk ### Method writeFile(options: WriteFileOptions) ### Parameters #### Request Body - **`options`** (`WriteFileOptions`) - Required - Options for writing the file. ### Since 1.0.0 ``` -------------------------------- ### ReaddirOptions Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Options for the readdir operation. ```APIDOC ## ReaddirOptions ### Description Options that can be provided to the readdir operation. ### Properties - **`path`** (string) - The path of the directory to read. - **`directory`** (Directory) - The `Directory` to list files from. ``` -------------------------------- ### readdir Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Return a list of files from the directory (not recursive). Accepts a ReaddirOptions object and returns a Promise resolving to a ReaddirResult. ```APIDOC ## readdir(...) ### Description Return a list of files from the directory (not recursive). ### Method ```typescript readdir(options: ReaddirOptions) => Promise ``` ### Parameters #### Request Body - **options** (ReaddirOptions) - Required - Options for reading the directory. ``` -------------------------------- ### Rename and Move Files with Capacitor Filesystem Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Use the `rename` method to move files or directories within the same or across different directories. This operation internally performs a copy-then-delete. ```typescript import { Filesystem, Directory } from '@capacitor/filesystem'; async function renameAndMoveFiles(): Promise { // Rename a file within the same directory await Filesystem.rename({ from: 'draft-report.docx', to: 'final-report.docx', directory: Directory.Documents, }); // Move a file from Cache to Documents await Filesystem.rename({ from: 'processed/output.json', to: 'saved/output.json', directory: Directory.Cache, toDirectory: Directory.Documents, }); // Rename a whole directory await Filesystem.rename({ from: 'old-folder', to: 'new-folder', directory: Directory.Data, }); console.log('Rename operations complete'); } ``` -------------------------------- ### Error Handling with Plugin Error Codes Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Provides guidance on handling errors thrown by the Filesystem plugin using specific error codes for more granular recovery logic. ```APIDOC ## Error Handling with Plugin Error Codes ### Description Since v7.1.0 the plugin throws structured errors with a `code` field on native Android and iOS. Catching by code allows fine-grained recovery logic. ### Common Error Codes - **OS-PLUG-FILE-0004** (iOS) - Bridge not initialized - **OS-PLUG-FILE-0005** (Both) - Invalid input parameters - **OS-PLUG-FILE-0006** (Both) - Invalid path - **OS-PLUG-FILE-0007** (Android) - Permission denied - **OS-PLUG-FILE-0008** (Both) - File/directory does not exist - **OS-PLUG-FILE-0009** (Android) - Operation not supported for input - **OS-PLUG-FILE-0010** (Both) - Directory already exists - **OS-PLUG-FILE-0011** (Both) - Missing parent directory - **OS-PLUG-FILE-0012** (Both) - Directory not empty (recursive=false) - **OS-PLUG-FILE-0013** (Both) - Generic OS failure ### Example Usage ```typescript import { Filesystem, Directory, Encoding } from '@capacitor/filesystem'; import type { PluginError } from '@capacitor/filesystem'; async function robustFileRead(path: string): Promise { try { const { data } = await Filesystem.readFile({ path, directory: Directory.Data, encoding: Encoding.UTF8, }); return data as string; } catch (err: any) { const code: string = (err as PluginError).code ?? ''; switch (code) { case 'OS-PLUG-FILE-0005': console.error('Invalid parameters provided'); break; case 'OS-PLUG-FILE-0006': console.error('Invalid path:', path); break; case 'OS-PLUG-FILE-0007': console.error('Permission denied — request permissions first'); break; case 'OS-PLUG-FILE-0008': console.warn('File not found:', path); break; case 'OS-PLUG-FILE-0013': console.error('Unknown OS-level error'); break; default: console.error('Unexpected error:', err); } return null; } } ``` ``` -------------------------------- ### rename Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Rename a file or directory. Accepts a RenameOptions object and returns a Promise. ```APIDOC ## rename(...) ### Description Rename a file or directory. ### Method ```typescript rename(options: RenameOptions) => Promise ``` ### Parameters #### Request Body - **options** (RenameOptions) - Required - Options for renaming the file or directory. ``` -------------------------------- ### readFile(...) Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Reads the content of a file from the disk. It takes an options object that specifies the file path and optionally the directory and encoding. ```APIDOC ## readFile(...) ### Description Read a file from disk ### Method readFile(options: ReadFileOptions) ### Parameters #### Request Body - **`options`** (`ReadFileOptions`) - Required - Options for reading the file. ### Returns `Promise` ### Since 1.0.0 ``` -------------------------------- ### deleteFile Source: https://context7.com/ionic-team/capacitor-filesystem/llms.txt Permanently deletes a file from disk. Throws `OS-PLUG-FILE-0008` if the file does not exist. ```APIDOC ## deleteFile(options) ### Description Permanently deletes a file from disk. Throws `OS-PLUG-FILE-0008` if the file does not exist. ### Method ```typescript Filesystem.deleteFile ``` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the file. - **directory** (Directory) - Required - The directory to read from. Possible values are `Directory.Documents`, `Directory.Data`, `Directory.Cache`, `Directory.External`, `Directory.ExternalCache`, `Directory.Local`. ### Request Example ```typescript await Filesystem.deleteFile({ path: "temp/temp1.json", directory: Directory.Cache }); ``` ### Response No specific response data is returned on success. ``` -------------------------------- ### StatOptions Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Options for the stat operation. ```APIDOC ## StatOptions ### Description Options that can be provided to the stat operation. ### Properties - **`path`** (string) - The path of the file to get data about. - **`directory`** (Directory) - The `Directory` to get the file under. ``` -------------------------------- ### ReadFileInChunksOptions Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Options for reading files in chunks. ```APIDOC ## ReadFileInChunksOptions ### Description Options for reading files in chunks. ### Parameters #### Query Parameters - **chunkSize** (number) - Required - Size of the chunks in bytes. ``` -------------------------------- ### FileInfo Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Represents information about a file or directory. ```APIDOC ## FileInfo ### Description Represents information about a file or directory. ### Properties - **`name`** (string) - Name of the file or directory. - **`type`** ('file' | 'directory') - Type of the file. - **`size`** (number) - Size of the file in bytes. - **`ctime`** (number) - Time of creation in milliseconds. It's not available on Android 7 and older devices. - **`mtime`** (number) - Time of last modification in milliseconds. - **`uri`** (string) - The uri of the file. ``` -------------------------------- ### downloadFile(...) Source: https://github.com/ionic-team/capacitor-filesystem/blob/main/README.md Downloads a file from a remote URL to the device's local storage. You can specify the URL, path, and directory. ```APIDOC ## downloadFile(...) ### Description Download a file from a remote URL to local storage ### Method downloadFile(options: DownloadFileOptions) ### Parameters #### Request Body - **`options`** (`DownloadFileOptions`) - Required - Options for downloading the file. ### Returns `Promise` ### Since 1.0.0 ```