Working with File System (expo-file-system)
1. Reading Files
| Method | Description | Return Type | Notes |
|---|---|---|---|
| FileSystem.readAsStringAsync() | Reads a file as a string | Promise<string> |
Supports UTF-8 encoding |
| FileSystem.readAsync() | Reads a file as a base64-encoded string | Promise<string> |
Useful for binary files |
| FileSystem.readAsStringAsync() | Reads a file as a string with custom encoding | Promise<string> |
Supports utf8, ascii, and base64 |
Example: Reading a Text File
import * as FileSystem from 'expo-file-system';
const fileUri = FileSystem.documentDirectory + 'sample.txt';
const content = await FileSystem.readAsStringAsync(fileUri);
console.log(content);
Example: Reading a Binary File
import * as FileSystem from 'expo-file-system';
const fileUri = FileSystem.documentDirectory + 'image.png';
const base64Content = await FileSystem.readAsync(fileUri);
console.log(base64Content);
Note: Ensure the file exists before attempting to read it, or handle the error appropriately.
2. Writing Files
| Method | Description | Parameters | Return Value |
|---|---|---|---|
| writeAsStringAsync | Writes text to a file asynchronously | fileUri: string, content: string, options?: WriteOptions |
Promise<void> |
| writeAsync | Writes binary data to a file asynchronously | fileUri: string, content: Uint8Array, options?: WriteOptions |
Promise<void> |
Example: Writing Text to a File
import * as FileSystem from 'expo-file-system';
const fileUri = FileSystem.documentDirectory + 'example.txt';
await FileSystem.writeAsStringAsync(fileUri, 'Hello, Expo!');
Example: Writing Binary Data to a File
import * as FileSystem from 'expo-file-system';
const fileUri = FileSystem.documentDirectory + 'image.png';
const data = new Uint8Array([0x89, 0x50, 0x4E, 0x47]); // PNG header
await FileSystem.writeAsync(fileUri, data);
Note: Ensure the directory exists before writing to a file. Use
makeDirectoryAsync if needed.
3. Deleting Files
| Method | Description | Notes |
|---|---|---|
| deleteAsync() | Deletes a file or directory at the specified path. | Can delete directories recursively if recursive is set to true. |
| deleteAsync() | Deletes a file or directory at the specified path. | Can delete directories recursively if recursive is set to true. |
Example: Delete a file
import * as FileSystem from 'expo-file-system';
const fileUri = FileSystem.documentDirectory + 'example.txt';
await FileSystem.deleteAsync(fileUri);
console.log('File deleted');
Example: Delete a directory recursively
import * as FileSystem from 'expo-file-system';
const dirUri = FileSystem.documentDirectory + 'myFolder';
await FileSystem.deleteAsync(dirUri, { recursive: true });
console.log('Directory deleted');
Note: Deleting a file or directory is irreversible. Ensure that the path is correct before deletion.
4. Downloading Files
| Property | Description | Values |
|---|---|---|
| downloadFile | Downloads a file from a URL to the device's file system | Promise<DownloadResult> |
Example: Downloading a file
import * as FileSystem from 'expo-file-system';
const downloadFile = async () => {
const { uri } = await FileSystem.downloadAsync(
'https://example.com/file.pdf',
FileSystem.documentDirectory + 'downloaded-file.pdf'
);
console.log('File downloaded to:', uri);
};
Note: The file will be downloaded to the app's document directory by default. Make sure to handle permissions if downloading to external storage.
| Property | Description | Values |
|---|---|---|
| uri | URI of the downloaded file | string |
| status | Status of the download operation | number |
| headers | Response headers from the server | Object |
Example: Download with progress tracking
import * as FileSystem from 'expo-file-system';
const downloadWithProgress = async () => {
const downloadResumable = FileSystem.createDownloadResumable(
'https://example.com/file.pdf',
FileSystem.documentDirectory + 'file.pdf',
{},
(progress) => {
console.log('Download progress:', progress.totalBytesWritten / progress.totalBytesExpectedToWrite * 100);
}
);
try {
const result = await downloadResumable.downloadAsync();
console.log('Downloaded file:', result);
} catch (error) {
console.error('Download failed:', error);
}
};
5. Uploading Files
Example: Upload a file to a server
import * as FileSystem from 'expo-file-system';
const uploadUrl = 'https://example.com/upload';
const fileUri = 'file:///path/to/local/file.txt';
const response = await FileSystem.uploadAsync(uploadUrl, fileUri, {
headers: {
'Content-Type': 'multipart/form-data',
},
mimeType: 'text/plain',
});
console.log('Upload response:', response);
| Option | Values | Description |
|---|---|---|
| uploadUrl | string |
The URL to upload the file to |
| fileUri | string |
The local file URI to upload |
| headers | object |
HTTP headers to include in the upload request |
| mimeType | string |
MIME type of the file being uploaded |
| fieldName | string |
Field name for the file in the multipart form (default: file) |
Note: The file must be accessible from the device’s file system. Files in
node_modules or other non-accessible locations cannot be uploaded.
Warning: Ensure that the server endpoint supports file uploads and is configured to handle
multipart/form-data.
6. Creating Directories
| Property | Description | Example |
|---|---|---|
| FileSystem.makeDirectoryAsync() | Creates a new directory at the specified path | import * as FileSystem from 'expo-file-system';\n\nconst directoryPath = FileSystem.documentDirectory + 'myNewFolder';\nawait FileSystem.makeDirectoryAsync(directoryPath);\nconsole.log('Directory created'); |
| FileSystem.makeDirectoryAsync(path, options) | Creates a new directory with optional settings | import * as FileSystem from 'expo-file-system';\n\nconst directoryPath = FileSystem.documentDirectory + 'myNewFolder';\nawait FileSystem.makeDirectoryAsync(directoryPath, {\n intermediates: true\n}); |
Note: The
intermediates option allows creating parent directories if they don't exist.7. Reading Directory Contents
| Property | Description | Example |
|---|---|---|
| FileSystem.readAsStringAsync() | Reads the contents of a file as a string | FileSystem.readAsStringAsync(FileSystem.documentDirectory + 'example.txt') |
| FileSystem.readAsync() | Reads the contents of a file as a base64-encoded string | FileSystem.readAsync(FileSystem.documentDirectory + 'image.png') |
| FileSystem.getInfoAsync() | Retrieves information about a file or directory | FileSystem.getInfoAsync(FileSystem.documentDirectory + 'example.txt') |
| FileSystem.readDirectoryAsync() | Lists the contents of a directory | FileSystem.readDirectoryAsync(FileSystem.documentDirectory) |
Example: Reading Directory Contents
import * as FileSystem from 'expo-file-system';
const directoryContents = await FileSystem.readDirectoryAsync(FileSystem.documentDirectory);
console.log(directoryContents); // Logs array of filenames in the directory
Example: Reading File Content as String
import * as FileSystem from 'expo-file-system';
const fileContent = await FileSystem.readAsStringAsync(
FileSystem.documentDirectory + 'data.json'
);
console.log(fileContent); // Logs file content as string
Example: Getting File Info
import * as FileSystem from 'expo-file-system';
const fileInfo = await FileSystem.getInfoAsync(
FileSystem.documentDirectory + 'data.json'
);
console.log(fileInfo.exists); // true or false
console.log(fileInfo.size); // Size in bytes
8. Getting File Info
| Property | Description | Values |
|---|---|---|
| fileInfo | Object containing file metadata | { uri, size, modTime, isDirectory } |
Example: Get file info
import * as FileSystem from 'expo-file-system';
const fileInfo = await FileSystem.getInfoAsync('file://path/to/file.txt');
console.log(fileInfo.size); // File size in bytes
console.log(fileInfo.modTime); // Last modified time
Note: The
uri property in the returned object is the full file path, which can be used to access the file later.
9. Moving Files
| Property | Description | Notes |
|---|---|---|
| moveFile | Moves a file from one location to another | Can move files between local storage and cache directories |
Example: Moving a File
import * as FileSystem from 'expo-file-system';
const sourceUri = FileSystem.documentDirectory + 'source.txt';
const destinationUri = FileSystem.cacheDirectory + 'destination.txt';
await FileSystem.moveFile({
from: sourceUri,
to: destinationUri,
});
Note: The destination path must include the filename and extension.
10. Copying Files
| Property | Description | Example |
|---|---|---|
| copyAsync(source, destination) | Copies a file from source to destination | import *amp;nbsp;{ copyAsync } from 'expo-file-system'; |
11. Using Document Directory
| Property | Description | Example |
|---|---|---|
| documentDirectory | Path to the document directory where app can store files. | file://var/mobile/Containers/Data/Application/.../Documents/ |
Example: Reading a file from Document Directory
import * as FileSystem from 'expo-file-system';
const fileUri = FileSystem.documentDirectory + 'example.txt';
const content = await FileSystem.readAsStringAsync(fileUri);
console.log(content);
Example: Writing to Document Directory
import * as FileSystem from 'expo-file-system';
const fileUri = FileSystem.documentDirectory + 'newFile.txt';
await FileSystem.writeAsStringAsync(fileUri, 'Hello, World!');
Note: Files stored in the document directory are persisted across app sessions and backups.
12. Using Cache Directory
The cache directory in Expo is a dedicated location for storing temporary files that can be safely deleted when the app is closed or when the system runs low on storage. It's particularly useful for caching downloaded assets like images, videos, or other media that the app might need to access quickly.
| Property | Description | Example |
|---|---|---|
| cacheDirectory | Read-only property that returns the path to the app's cache directory. | file:// + cacheDirectory |
Example: Accessing the Cache Directory
import * as FileSystem from 'expo-file-system';
const cacheDir = FileSystem.cacheDirectory;
console.log("Cache Directory Path:", cacheDir);
Note: The cache directory is managed by the system and may be cleared automatically when the app is closed or under low storage conditions.