Expo FileSystem
A library that provides access to the local file system on the device.
expo-file-system provides access to a file system stored locally on the device. It is also capable of uploading and downloading files from network URLs.
How expo-file-system works differently inside of the Expo Go app
Within Expo Go, each project has a separate file system scope and has no access to the file system of other projects.
Installation
- npx expo install expo-file-systemIf you are installing this in an existing React Native app, make sure to install expo in your project.
Usage
Downloading files
const callback = downloadProgress => { const progress = downloadProgress.totalBytesWritten / downloadProgress.totalBytesExpectedToWrite; this.setState({ downloadProgress: progress, }); }; const downloadResumable = FileSystem.createDownloadResumable( 'http://techslides.com/demos/sample-videos/small.mp4', FileSystem.documentDirectory + 'small.mp4', {}, callback ); try { const { uri } = await downloadResumable.downloadAsync(); console.log('Finished downloading to ', uri); } catch (e) { console.error(e); } try { await downloadResumable.pauseAsync(); console.log('Paused download operation, saving for future retrieval'); AsyncStorage.setItem('pausedDownload', JSON.stringify(downloadResumable.savable())); } catch (e) { console.error(e); } try { const { uri } = await downloadResumable.resumeAsync(); console.log('Finished downloading to ', uri); } catch (e) { console.error(e); } //To resume a download across app restarts, assuming the DownloadResumable.savable() object was stored: const downloadSnapshotJson = await AsyncStorage.getItem('pausedDownload'); const downloadSnapshot = JSON.parse(downloadSnapshotJson); const downloadResumable = new FileSystem.DownloadResumable( downloadSnapshot.url, downloadSnapshot.fileUri, downloadSnapshot.options, callback, downloadSnapshot.resumeData ); try { const { uri } = await downloadResumable.resumeAsync(); console.log('Finished downloading to ', uri); } catch (e) { console.error(e); }
Managing Giphy's
import * as FileSystem from 'expo-file-system'; const gifDir = FileSystem.cacheDirectory + 'giphy/'; const gifFileUri = (gifId: string) => gifDir + `gif_${gifId}_200.gif`; const gifUrl = (gifId: string) => `https://media1.giphy.com/media/${gifId}/200.gif`; // Checks if gif directory exists. If not, creates it async function ensureDirExists() { const dirInfo = await FileSystem.getInfoAsync(gifDir); if (!dirInfo.exists) { console.log("Gif directory doesn't exist, creating…"); await FileSystem.makeDirectoryAsync(gifDir, { intermediates: true }); } } // Downloads all gifs specified as array of IDs export async function addMultipleGifs(gifIds: string[]) { try { await ensureDirExists(); console.log('Downloading', gifIds.length, 'gif files…'); await Promise.all(gifIds.map(id => FileSystem.downloadAsync(gifUrl(id), gifFileUri(id)))); } catch (e) { console.error("Couldn't download gif files:", e); } } // Returns URI to our local gif file // If our gif doesn't exist locally, it downloads it export async function getSingleGif(gifId: string) { await ensureDirExists(); const fileUri = gifFileUri(gifId); const fileInfo = await FileSystem.getInfoAsync(fileUri); if (!fileInfo.exists) { console.log("Gif isn't cached locally. Downloading…"); await FileSystem.downloadAsync(gifUrl(gifId), fileUri); } return fileUri; } // Exports shareable URI - it can be shared outside your app export async function getGifContentUri(gifId: string) { return FileSystem.getContentUriAsync(await getSingleGif(gifId)); } // Deletes whole giphy directory with all its content export async function deleteAllGifs() { console.log('Deleting all GIF files…'); await FileSystem.deleteAsync(gifDir); }
Server: handling multipart requests
The simple server in Node.js, which can save uploaded images to disk:
const express = require('express'); const app = express(); const fs = require('fs'); const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); // This method will save the binary content of the request as a file. app.patch('/binary-upload', (req, res) => { req.pipe(fs.createWriteStream('./uploads/image' + Date.now() + '.png')); res.end('OK'); }); // This method will save a "photo" field from the request as a file. app.patch('/multipart-upload', upload.single('photo'), (req, res) => { // You can access other HTTP parameters. They are located in the body object. console.log(req.body); res.end('OK'); }); app.listen(3000, () => { console.log('Working on port 3000'); });
API
import * as FileSystem from 'expo-file-system';
Directories
The API takes file:// URIs pointing to local files on the device to identify files. Each app only has read and write access to locations under the following directories:
So, for example, the URI to a file named 'myFile' under 'myDirectory' in the app's user documents directory would be FileSystem.documentDirectory + 'myDirectory/myFile'.
Expo APIs that create files generally operate within these directories. This includes Audio recordings, Camera photos, ImagePicker results, SQLite databases and takeSnapShotAsync() results. This allows their use with the FileSystem API.
Some FileSystem functions are able to read from (but not write to) other locations.
SAF URI
A SAF URI is a URI that is compatible with the Storage Access Framework. It should look like this content://com.android.externalstorage.*.
The easiest way to obtain such URI is by requestDirectoryPermissionsAsync method.
Classes
Type: Class extends FileSystemDirectory
Represents a directory on the filesystem.
A Directory instance can be created for any path, and does not need to exist on the filesystem during creation.
The constructor accepts an array of strings that are joined to create the directory URI. The first argument can also be a Directory instance (like Paths.cache).
Example
const directory = new Directory(Paths.cache, "subdirName");
Directory Properties
unionA size of the directory in bytes. Null if the directory does not exist, or it cannot be read.
Acceptable values are: null | number
stringRepresents the directory URI. The field is read-only, but it may change as a result of calling some methods such as move.
Directory Methods
Copies a directory.
void| Parameter | Type |
|---|---|
| options(optional) | DirectoryCreateOptions |
Creates a directory that the current uri points to.
voidDeletes a directory. Also deletes all files and directories inside the directory.
voidRetrieves an object containing properties of a directory.
DirectoryInfoAn object with directory metadata (for example, size, creation date, and so on).
Moves a directory. Updates the uri property that now points to the new location.
void| Parameter | Type | Description |
|---|---|---|
| initialUri(optional) | string | An optional uri pointing to an initial folder on which the directory picker is opened. |
A static method that opens a file picker to select a directory.
On iOS, the selected directory grants temporary read and write access for the current app session only. After the app restarts, you must prompt the user again to regain access.
a Directory instance. On Android, the underlying uri will be a content URI.
Type: Class extends FileSystemFile implements Blob
Represents a file on the filesystem.
A File instance can be created for any path, and does not need to exist on the filesystem during creation.
The constructor accepts an array of strings that are joined to create the file URI. The first argument can also be a Directory instance (like Paths.cache) or a File instance (which creates a new reference to the same file).
Example
const file = new File(Paths.cache, "subdirName", "file.txt");
File Properties
unionA creation time of the file expressed in milliseconds since epoch. Returns null if the file does not exist, cannot be read or the Android version is earlier than API 26.
Acceptable values are: null | number
booleanA boolean representing if a file exists. true if the file exists, false otherwise.
Also, false if the application does not have read access to the file.
unionA md5 hash of the file. Null if the file does not exist, or it cannot be read.
Acceptable values are: null | string
unionA last modification time of the file expressed in milliseconds since epoch. Returns a Null if the file does not exist, or it cannot be read.
Acceptable values are: null | number
numberA size of the file in bytes. 0 if the file does not exist, or it cannot be read.
stringA mime type of the file. An empty string if the file does not exist, or it cannot be read.
stringRepresents the file URI. The field is read-only, but it may change as a result of calling some methods such as move.
File Methods
The arrayBuffer() method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer.
Promise<ArrayBuffer>Retrieves content of the file as base64.
Promise<string>A promise that resolves with the contents of the file as a base64 string.
Retrieves content of the file as base64.
stringThe contents of the file as a base64 string.
Retrieves byte content of the entire file.
Promise<Uint8Array<ArrayBuffer>>A promise that resolves with the contents of the file as a Uint8Array.
Retrieves byte content of the entire file.
Uint8ArrayThe contents of the file as a Uint8Array.
| Parameter | Type | Description |
|---|---|---|
| url | string | The URL of the file to download. |
| destination | Directory | File | The destination directory or file. If a directory is provided, the resulting filename will be determined based on the response headers. |
| options(optional) | DownloadOptions | Download options. When the destination already contains a file, the promise rejects with a |
A static method that downloads a file from the network.
On Android, the response body streams directly into the target file. If the download fails after it starts, a partially written file may remain at the destination. On iOS, the download first completes in a temporary location and the file is moved into place only after success, so no file is left behind when the request fails.
A promise that resolves to the downloaded file. When the server responds with
a non-2xx HTTP status, the promise rejects with an UnableToDownload error whose
message includes the status code. No file is created in that scenario.
Example
const file = await File.downloadFileAsync("https://example.com/image.png", new Directory(Paths.document));
| Parameter | Type |
|---|---|
| options(optional) | InfoOptions |
Retrieves an object containing properties of a file
FileInfoAn object with file metadata (for example, size, creation date, and so on).
Moves a directory. Updates the uri property that now points to the new location.
voidReturns A FileHandle object that can be used to read and write data to the file.
FileHandle| Parameter | Type | Description |
|---|---|---|
| initialUri(optional) | string | An optional URI pointing to an initial folder on which the file picker is opened. |
| mimeType(optional) | string | A mime type that is used to filter out files that can be picked out. |
ReadableStream<Uint8Array<ArrayBuffer>>| Parameter | Type |
|---|---|
| start(optional) | number |
| end(optional) | number |
| contentType(optional) | string |
The slice() method of the Blob interface creates and returns a new Blob object which contains data from a subset of the blob on which it's called.
BlobThe stream() method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob.
ReadableStream<Uint8Array<ArrayBuffer>>Retrieves text from the file.
Promise<string>A promise that resolves with the contents of the file as string.
Retrieves text from the file.
stringThe contents of the file as string.
WritableStream<Uint8Array>| Parameter | Type | Description |
|---|---|---|
| content | string | Uint8Array | The content to write into the file. |
Writes content to the file.
voidFileHandle Properties
unionA property that indicates the current byte offset in the file. Calling readBytes or writeBytes will read or write a specified amount of bytes starting from this offset. The offset is incremented by the number of bytes read or written.
The offset can be set to any value within the file size. If the offset is set to a value greater than the file size, the next write operation will append data to the end of the file.
Null if the file handle is closed.
Acceptable values are: null | number
FileHandle Methods
Closes the file handle. This allows the file to be deleted, moved or read by a different process. Subsequent calls to readBytes or writeBytes will throw an error.
void| Parameter | Type | Description |
|---|---|---|
| length | number | The number of bytes to read. |
Reads the specified amount of bytes from the file at the current offset.
Uint8Array<ArrayBuffer>| Parameter | Type | Description |
|---|---|---|
| bytes | Uint8Array | A |
Writes the specified bytes to the file at the current offset.
voidType: Class extends PathUtilities
Paths Properties
Record<string, Directory>numberA property that represents the available space on device's internal storage, represented in bytes.
DirectoryA property containing the bundle directory – the directory where assets bundled with the application are stored.
DirectoryA property containing the cache directory – a place to store files that can be deleted by the system when the device runs low on storage.
DirectoryA property containing the document directory – a place to store files that are safe from being deleted by the system.
Paths Methods
| Parameter | Type | Description |
|---|---|---|
| path | string | File | Directory | The path to get the base name from. |
| ext(optional) | string | An optional file extension. |
Returns the base name of a path.
stringA string representing the base name.
Returns the directory name of a path.
stringA string representing the directory name.
Returns the extension of a path.
stringA string representing the extension.
| Parameter | Type |
|---|---|
| ...uris | string[] |
Returns an object that indicates if the specified path represents a directory.
PathInfoChecks if a path is absolute.
booleantrue if the path is absolute, false otherwise.
Joins path segments into a single path.
stringA string representing the joined path.
Normalizes a path.
stringA string representing the normalized path.
Parses a path into its components.
{
base: string,
dir: string,
ext: string,
name: string,
root: string
}An object containing the parsed path components.
Methods
Deprecated: Use
new File().copy()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| options | RelocatingOptions |
Promise<void>Deprecated: Import this method from
expo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| uri | string |
| fileUri | string |
| options(optional) | DownloadOptions |
| callback(optional) | FileSystemNetworkTaskProgressCallback<DownloadProgressData> |
| resumeData(optional) | string |
anyDeprecated: Import this method from
expo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| url | string |
| fileUri | string |
| options(optional) | FileSystemUploadOptions |
| callback(optional) | FileSystemNetworkTaskProgressCallback<UploadProgressData> |
anyDeprecated: Use
new File().delete()ornew Directory().delete()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| fileUri | string |
| options(optional) | DeletingOptions |
Promise<void>Deprecated: Use
File.downloadFileAsyncor import this method fromexpo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| uri | string |
| fileUri | string |
| options(optional) | DownloadOptions |
Promise<FileSystemDownloadResult>Deprecated: Import this method from
expo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| fileUri | string |
Promise<string>Deprecated: Use
Paths.availableDiskSpaceor import this method fromexpo-file-system/legacy. This method will throw in runtime.
Promise<number>Deprecated: Use
new File().infoor import this method fromexpo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| fileUri | string |
| options(optional) | InfoOptions |
Deprecated: Use
Paths.totalDiskSpaceor import this method fromexpo-file-system/legacy. This method will throw in runtime.
Promise<number>Deprecated: Use
new Directory().create()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| fileUri | string |
| options(optional) | MakeDirectoryOptions |
Promise<void>Deprecated: Use
new File().move()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| options | RelocatingOptions |
Promise<void>Deprecated: Use
new File().text()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| fileUri | string |
| options(optional) | ReadingOptions |
Promise<string>Deprecated: Use
new Directory().list()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| fileUri | string |
Promise<string[]>Deprecated: Use
@expo/fetchor import this method fromexpo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| url | string |
| fileUri | string |
| options(optional) | FileSystemUploadOptions |
Promise<FileSystemUploadResult>Deprecated: Use
new File().write()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
| Parameter | Type |
|---|---|
| fileUri | string |
| contents | string |
| options(optional) | WritingOptions |
Promise<void>Types
| Property | Type | Description |
|---|---|---|
| idempotent(optional) | boolean | This flag controls whether the If Default: false |
| intermediates(optional) | boolean | Whether to create intermediate directories if they do not exist. Default: false |
| overwrite(optional) | boolean | Whether to overwrite the directory if it exists. Default: false |
| Property | Type | Description |
|---|---|---|
| creationTime(optional) | number | A creation time of the directory expressed in milliseconds since epoch. Returns null if the Android version is earlier than API 26. |
| exists | boolean | Indicates whether the directory exists. |
| files(optional) | string[] | A list of file names contained within a directory. |
| modificationTime(optional) | number | The last modification time of the directory expressed in milliseconds since epoch. |
| size(optional) | number | The size of the file in bytes. |
| uri(optional) | string | A |
| Property | Type | Description |
|---|---|---|
| headers(optional) | undefined | The headers to send with the request. |
| idempotent(optional) | boolean | This flag controls whether the If Default: false |
| Property | Type | Description |
|---|---|---|
| intermediates(optional) | boolean | Whether to create intermediate directories if they do not exist. Default: false |
| overwrite(optional) | boolean | Whether to overwrite the file if it exists. Default: false |
| Property | Type | Description |
|---|---|---|
| creationTime(optional) | number | A creation time of the file expressed in milliseconds since epoch. Returns null if the Android version is earlier than API 26. |
| exists | boolean | Indicates whether the file exists. |
| md5(optional) | string | Present if the |
| modificationTime(optional) | number | The last modification time of the file expressed in milliseconds since epoch. |
| size(optional) | number | The size of the file in bytes. |
| uri(optional) | string | A |
| Property | Type | Description |
|---|---|---|
| md5(optional) | boolean | Whether to return the MD5 hash of the file. Default: false |
| Property | Type | Description |
|---|---|---|
| exists | boolean | Indicates whether the path exists. Returns true if it exists; false if the path does not exist or if there is no read permission. |
| isDirectory | boolean | null | Indicates whether the path is a directory. Returns true or false if the path exists; otherwise, returns null. |
Supported URI schemes
In this table, you can see what type of URI can be handled by each method. For example, if you have an URI, which begins with content://, you cannot use FileSystem.readAsStringAsync(), but you can use FileSystem.copyAsync() which supports this scheme.
| Method name | Android | iOS |
|---|---|---|
getInfoAsync | file:///,content://,asset://,no scheme | file://,ph://,assets-library:// |
readAsStringAsync | file:///,asset://,SAF URI | file:// |
writeAsStringAsync | file:///,SAF URI | file:// |
deleteAsync | file:///,SAF URI | file:// |
moveAsync | Source:file:///,SAF URI Destination: file:// | Source:file://Destination: file:// |
copyAsync | Source:file:///,content://,asset://,SAF URI, no scheme Destination: file:// | Source:file://,ph://,assets-library://Destination: file:// |
makeDirectoryAsync | file:/// | file:// |
readDirectoryAsync | file:/// | file:// |
downloadAsync | Source:http://,https://Destination: file:/// | Source:http://,https://Destination: file:// |
uploadAsync | Source:file:///Destination: http://https:// | Source:file://Destination: http://https:// |
createDownloadResumable | Source:http://,https://Destination: file:/// | Source:http://,https://Destination: file:// |
On Android no scheme defaults to a bundled resource.
Permissions
Android
The following permissions are added automatically through this library's AndroidManifest.xml.
| Android Permission | Description |
|---|---|
Allows an application to read from external storage. | |
Allows an application to write to external storage. | |
Allows applications to open network sockets. |
iOS
No permissions required.