What is @capacitor/filesystem?
@capacitor/filesystem is a Capacitor plugin that provides a set of APIs for reading, writing, and managing files on the device's filesystem. It allows developers to interact with the filesystem in a way that is consistent across different platforms, such as iOS, Android, and the web.
What are @capacitor/filesystem's main functionalities?
Read a file
This feature allows you to read the contents of a file from the device's filesystem. The code sample demonstrates how to read a file named 'text.txt' from the 'Documents' directory and log its contents to the console.
const { Filesystem, Directory } = require('@capacitor/filesystem');
async function readFile() {
try {
const contents = await Filesystem.readFile({
path: 'secrets/text.txt',
directory: Directory.Documents,
encoding: 'utf8'
});
console.log('File contents:', contents.data);
} catch (e) {
console.error('Unable to read file', e);
}
}
readFile();
Write a file
This feature allows you to write data to a file on the device's filesystem. The code sample demonstrates how to write the string 'This is a test' to a file named 'text.txt' in the 'Documents' directory.
const { Filesystem, Directory } = require('@capacitor/filesystem');
async function writeFile() {
try {
await Filesystem.writeFile({
path: 'secrets/text.txt',
data: 'This is a test',
directory: Directory.Documents,
encoding: 'utf8'
});
console.log('File written successfully');
} catch (e) {
console.error('Unable to write file', e);
}
}
writeFile();
Delete a file
This feature allows you to delete a file from the device's filesystem. The code sample demonstrates how to delete a file named 'text.txt' from the 'Documents' directory.
const { Filesystem, Directory } = require('@capacitor/filesystem');
async function deleteFile() {
try {
await Filesystem.deleteFile({
path: 'secrets/text.txt',
directory: Directory.Documents
});
console.log('File deleted successfully');
} catch (e) {
console.error('Unable to delete file', e);
}
}
deleteFile();
Create a directory
This feature allows you to create a new directory on the device's filesystem. The code sample demonstrates how to create a directory named 'secrets' in the 'Documents' directory.
const { Filesystem, Directory } = require('@capacitor/filesystem');
async function createDirectory() {
try {
await Filesystem.mkdir({
path: 'secrets',
directory: Directory.Documents,
recursive: false
});
console.log('Directory created successfully');
} catch (e) {
console.error('Unable to create directory', e);
}
}
createDirectory();
List files in a directory
This feature allows you to list all files in a specified directory on the device's filesystem. The code sample demonstrates how to list all files in the 'secrets' directory within the 'Documents' directory.
const { Filesystem, Directory } = require('@capacitor/filesystem');
async function listFiles() {
try {
const result = await Filesystem.readdir({
path: 'secrets',
directory: Directory.Documents
});
console.log('Files in directory:', result.files);
} catch (e) {
console.error('Unable to list files', e);
}
}
listFiles();
Other packages similar to @capacitor/filesystem
react-native-fs
react-native-fs is a file system library for React Native that provides similar functionalities to @capacitor/filesystem, such as reading, writing, and managing files. It is specifically designed for React Native applications and offers a wide range of file system operations.
cordova-plugin-file
cordova-plugin-file is a Cordova plugin that allows for file system access and management on mobile devices. It provides a similar set of APIs to @capacitor/filesystem, enabling developers to read, write, and manage files across different platforms. It is widely used in Cordova-based projects.
expo-file-system
expo-file-system is a file system API for Expo and React Native applications. It offers functionalities similar to @capacitor/filesystem, such as reading, writing, and managing files. It is designed to work seamlessly with the Expo ecosystem and provides a consistent API across different platforms.
@capacitor/filesystem
The Filesystem API provides a NodeJS-like API for working with files on the device.
Install
npm install @capacitor/filesystem
npx cap sync
Understanding Directories and Files
iOS and Android have additional layers of separation between files, such as special directories that are backed up to the Cloud, or ones for storing Documents. The Filesystem API offers a simple way to scope each operation to a specific special directory on the device.
Additionally, the Filesystem API supports using full file://
paths, or reading content://
files on Android. Simply leave out the directory
param to use a full file path.
Example
import { Filesystem, FilesystemDirectory, FilesystemEncoding } from '@capacitor/core';
const writeSecretFile = async () {
await Filesystem.writeFile({
path: 'secrets/text.txt',
data: "This is a test",
directory: FilesystemDirectory.Documents,
encoding: FilesystemEncoding.UTF8,
});
};
const readSecretFile = async () {
const contents = await Filesystem.readFile({
path: 'secrets/text.txt',
directory: FilesystemDirectory.Documents,
encoding: FilesystemEncoding.UTF8,
});
console.log('secrets:', contents);
};
const deleteSecretFile = async () {
await Filesystem.deleteFile({
path: 'secrets/text.txt',
directory: FilesystemDirectory.Documents,
});
};
const readFilePath = async () {
const contents = await Filesystem.readFile({
path: 'file:///var/mobile/Containers/Data/Application/22A433FD-D82D-4989-8BE6-9FC49DEA20BB/Documents/text.txt'
});
console.log('data:', contents);
};
API
readFile(...)
readFile(options: ReadFileOptions) => Promise<ReadFileResult>
Read a file from disk
Returns: Promise<ReadFileResult>
Since: 1.0.0
writeFile(...)
writeFile(options: WriteFileOptions) => Promise<WriteFileResult>
Write a file to disk in the specified location on device
Returns: Promise<WriteFileResult>
Since: 1.0.0
appendFile(...)
appendFile(options: AppendFileOptions) => Promise<void>
Append to a file on disk in the specified location on device
Since: 1.0.0
deleteFile(...)
deleteFile(options: DeleteFileOptions) => Promise<void>
Delete a file from disk
Since: 1.0.0
mkdir(...)
mkdir(options: MkdirOptions) => Promise<void>
Create a directory.
Since: 1.0.0
rmdir(...)
rmdir(options: RmdirOptions) => Promise<void>
Remove a directory
Since: 1.0.0
readdir(...)
readdir(options: ReaddirOptions) => Promise<ReaddirResult>
Return a list of files from the directory (not recursive)
Returns: Promise<ReaddirResult>
Since: 1.0.0
getUri(...)
getUri(options: GetUriOptions) => Promise<GetUriResult>
Return full File URI for a path and directory
Returns: Promise<GetUriResult>
Since: 1.0.0
stat(...)
stat(options: StatOptions) => Promise<StatResult>
Return data about a file
Returns: Promise<StatResult>
Since: 1.0.0
rename(...)
rename(options: RenameOptions) => Promise<void>
Rename a file or directory
Since: 1.0.0
copy(...)
copy(options: CopyOptions) => Promise<void>
Copy a file or directory
Since: 1.0.0
checkPermissions()
checkPermissions() => Promise<PermissionStatus>
Check read/write permissions.
Required on Android, only when using Directory.Documents
or
Directory.ExternalStorage
.
Returns: Promise<PermissionStatus>
Since: 1.0.0
requestPermissions()
requestPermissions() => Promise<PermissionStatus>
Request read/write permissions.
Required on Android, only when using Directory.Documents
or
Directory.ExternalStorage
.
Returns: Promise<PermissionStatus>
Since: 1.0.0
Interfaces
ReadFileResult
Prop | Type | Description | Since |
---|
data | string | The string representation of the data contained in the file | 1.0.0 |
ReadFileOptions
Prop | Type | Description | Since |
---|
path | string | The path of the file to read | 1.0.0 |
directory | Directory | The Directory to read the file from | 1.0.0 |
encoding | Encoding | The encoding to read the file in, if not provided, data is read as binary and returned as base64 encoded. Pass Encoding.UTF8 to read data as string | 1.0.0 |
WriteFileResult
Prop | Type | Description | Since |
---|
uri | string | The uri where the file was written into | 1.0.0 |
WriteFileOptions
Prop | Type | Description | Default | Since |
---|
path | string | The path of the file to write | | 1.0.0 |
data | string | The data to write | | 1.0.0 |
directory | Directory | The Directory to store the file in | | 1.0.0 |
encoding | Encoding | The encoding to write the file in. If not provided, data is written as base64 encoded. Pass Encoding.UTF8 to write data as string | | 1.0.0 |
recursive | boolean | Whether to create any missing parent directories. | false | 1.0.0 |
AppendFileOptions
Prop | Type | Description | Since |
---|
path | string | The path of the file to append | 1.0.0 |
data | string | The data to write | 1.0.0 |
directory | Directory | The Directory to store the file in | 1.0.0 |
encoding | Encoding | The encoding to write the file in. If not provided, data is written as base64 encoded. Pass FilesystemEncoding.UTF8 to write data as string | 1.0.0 |
DeleteFileOptions
Prop | Type | Description | Since |
---|
path | string | The path of the file to delete | 1.0.0 |
directory | Directory | The Directory to delete the file from | 1.0.0 |
MkdirOptions
Prop | Type | Description | Default | Since |
---|
path | string | The path of the new directory | | 1.0.0 |
directory | Directory | The Directory to make the new directory in | | 1.0.0 |
recursive | boolean | Whether to create any missing parent directories as well. | false | 1.0.0 |
RmdirOptions
Prop | Type | Description | Default | Since |
---|
path | string | The path of the directory to remove | | 1.0.0 |
directory | Directory | The Directory to remove the directory from | | 1.0.0 |
recursive | boolean | Whether to recursively remove the contents of the directory | false | 1.0.0 |
ReaddirResult
Prop | Type | Description | Since |
---|
files | string[] | List of files and directories inside the directory | 1.0.0 |
ReaddirOptions
Prop | Type | Description | Since |
---|
path | string | The path of the directory to read | 1.0.0 |
directory | Directory | The Directory to list files from | 1.0.0 |
GetUriResult
Prop | Type | Description | Since |
---|
uri | string | The uri of the file | 1.0.0 |
GetUriOptions
Prop | Type | Description | Since |
---|
path | string | The path of the file to get the URI for | 1.0.0 |
directory | Directory | The Directory to get the file under | 1.0.0 |
StatResult
Prop | Type | Description | Since |
---|
type | string | Type of the file | 1.0.0 |
size | number | Size of the file | 1.0.0 |
ctime | number | Time of creation | 1.0.0 |
mtime | number | Time of last modification | 1.0.0 |
uri | string | The uri of the file | 1.0.0 |
StatOptions
Prop | Type | Description | Since |
---|
path | string | The path of the file to get data about | 1.0.0 |
directory | Directory | The Directory to get the file under | 1.0.0 |
CopyOptions
Prop | Type | Description | Since |
---|
from | string | The existing file or directory | 1.0.0 |
to | string | The destination file or directory | 1.0.0 |
directory | Directory | The Directory containing the existing file or directory | 1.0.0 |
toDirectory | Directory | The Directory containing the destination file or directory. If not supplied will use the 'directory' parameter as the destination | 1.0.0 |
PermissionStatus
Type Aliases
RenameOptions
CopyOptions
PermissionState
'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'
Enums
Directory
Members | Value | Description | Since |
---|
Documents | 'DOCUMENTS' | The Documents directory On iOS it's the app's documents directory. Use this directory to store user-generated content. On Android it's the Public Documents folder, so it's accessible from other apps. It's not accesible on Android 10 unless the app enables legacy External Storage by adding android:requestLegacyExternalStorage="true" in the application tag in the AndroidManifest.xml | 1.0.0 |
Data | 'DATA' | The Data directory On iOS it will use the Documents directory On Android it's the directory holding application files. Files will be deleted when the application is uninstalled. | 1.0.0 |
Cache | 'CACHE' | The Cache directory Can be deleted in cases of low memory, so use this directory to write app-specific files that your app can re-create easily. | 1.0.0 |
External | 'EXTERNAL' | The external directory On iOS it will use the Documents directory On Android it's the directory on the primary shared/external storage device where the application can place persistent files it owns. These files are internal to the applications, and not typically visible to the user as media. Files will be deleted when the application is uninstalled. | 1.0.0 |
ExternalStorage | 'EXTERNAL_STORAGE' | The external storage directory On iOS it will use the Documents directory On Android it's the primary shared/external storage directory. It's not accesible on Android 10 unless the app enables legacy External Storage by adding android:requestLegacyExternalStorage="true" in the application tag in the AndroidManifest.xml | 1.0.0 |
Encoding
Members | Value | Description | Since |
---|
UTF8 | 'utf8' | Eight-bit UCS Transformation Format | 1.0.0 |
ASCII | 'ascii' | Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set This encoding is only supported on Android. | 1.0.0 |
UTF16 | 'utf16' | Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark This encoding is only supported on Android. | 1.0.0 |