This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
This is documentation for the next SDK version. For up-to-date documentation, see the latest version (SDK 57).
Expo FileSystem
A library that provides access to the local file system on the device.
expo-file-system provides access to files and directories stored on a device or bundled as assets into the native project. It also allows downloading files from the network.
Installation
If you are installing this in an existing React Native app, make sure to install expo in your project.
Configuration in app config
You can configure expo-file-system using its built-in config plugin if you use config plugins in your project (Continuous Native Generation (CNG)). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect. If your app does not use CNG, then you'll need to manually configure the library.
Example app.json with config plugin
Configurable properties
Are you using this library in an existing React Native app?
If you're not using Continuous Native Generation (CNG) or you're using native ios project manually, then you need to add the LSSupportsOpeningDocumentsInPlace and UIFileSharingEnabled keys to your project's ios/[app]/Info.plist:
<key>LSSupportsOpeningDocumentsInPlace</key> <true/> <key>UIFileSharingEnabled</key> <true/>
Usage
import { File, Directory, Paths } from 'expo-file-system';
The File and Directory instances hold a reference to a file, content, or asset URI.
The file or directory does not need to exist — an error will be thrown from the constructor only if the wrong class is used to represent an existing path (so if you try to create a File instance passing a path to an already existing directory).
Features
- Both synchronous and asynchronous, read and write access to file contents
- Creation, modification and deletion
- Available properties, such as
type,size,creationDate, and more - Ability to read and write files as streams or using the
FileHandleclass - Easy file download/upload using
downloadFileAsyncorexpo/fetch - File previews using platform-native flows
Examples
Picking files using system pickers
Usage with expo-document-picker:
Using the built-in pickFileAsync or pickDirectoryAsync method on Android:
Previewing files
Use File.preview() to open a local file with the platform's file preview flow. File preview is currently supported on Android and iOS. On iOS, this presents Quick Look, which supports many common file types such as PDFs, images, text files, CSV files, and Office documents. On Android, this opens an ACTION_VIEW intent, so support depends on apps installed on the device that can handle the file's MIME type.
The mimeType option defaults to the file's type property. If the file extension does not identify the type correctly, pass mimeType explicitly, especially on Android where the MIME type is used to find compatible apps. When Android cannot resolve a MIME type, canPreview() resolves to false and preview() rejects.
canPreview() rejects if the file is invalid or cannot be read. It resolves to false when the file does not exist or when the platform cannot preview it.
preview() resolves once the native preview has been presented or handed off to another app. It rejects if the file does not exist, cannot be read, or no preview is available. It does not wait for the user to dismiss the viewer.
If a share sheet is useful in your app, you can compose this with expo-sharing when previewing fails:
Uploading files using expo/fetch
You can upload files as blobs directly with fetch built into the Expo package:
Or using the FormData constructor:
Random-access reads with FileHandle
Use FileHandle for efficient, random-access reads of large files without loading the entire file into memory. Obtain a handle by calling file.open(), read or write at any position using the offset property, and always close the handle when finished.
API
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: number | null
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
Deletes 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.
Promise<void>Moves a directory synchronously. Updates the uri property that now points to the new location.
voidWatches this directory for changes to its contents or the directory itself.
Events are emitted when files or subdirectories are created, modified, deleted, or renamed
within this directory. On iOS, child changes are surfaced as a coarse-grained modified event
on the directory itself, so filtering for child-level created, deleted, or renamed events
is not reliable. The watcher automatically stops when the directory is deleted or renamed.
To stop watching manually, call remove() on the returned subscription.
WatchSubscriptionA subscription handle. Call remove() to stop watching.
Example
const cacheDir = new Directory(Paths.cache); const subscription = cacheDir.watch((event) => { console.log(`${event.type}: ${event.target.uri}`); }); // Later, stop watching: subscription.remove();
Represents a download task with pause/resume support and progress tracking.
Download tasks start in the idle state. Calling downloadAsync() moves the task to active;
pausing moves it to paused, and a completed, cancelled, or failed transfer moves it to the
corresponding terminal state.
DownloadTask Properties
DownloadTask Methods
Adds a listener for download progress events.
Note: Prefer the
onProgressoption unless you need manual subscription control.
EventSubscriptionA subscription handle. Call remove() to stop listening.
Cancels the download operation.
If downloadAsync() or resumeAsync() is pending, its promise is rejected after the native
request is cancelled. Calling this method after the task reaches completed, cancelled, or
error has no effect.
voidStarts the download operation.
This method can only be called once, while the task is idle. The promise resolves with
the downloaded file when the transfer completes, or with null if the task is paused before
completion. It is rejected when the request fails or the task is cancelled.
If options.signal is aborted, the promise is rejected with an AbortError.
A promise that resolves to the downloaded file, or null when the task is paused.
Creates a paused download task from saved state.
Use this to continue a download after persisting the value returned by savable(). New options
can attach progress callbacks or an abort signal because functions and signals are not stored
in DownloadPauseState. If both saved state and new options include headers, the new headers
override saved headers with the same names.
DownloadTaskA download task in the paused state.
Requests pausing the active download operation.
The pending downloadAsync() or resumeAsync() promise resolves with null after native
code produces resume data and the task enters the paused state. Use pauseAsync() if you
need to wait until the task is ready to resume or save.
voidRequests pausing the active download operation and waits until the task reaches the paused
state.
Promise<void>A promise that resolves after resume data is available.
Releases the native task handle.
Call this when you no longer need the task and want to release native resources manually.
voidResumes a paused download operation.
The promise resolves with the downloaded file when the transfer completes, or with null
if the task is paused again before completion. It is rejected when the request fails or the task
is cancelled.
A promise that resolves to the downloaded file, or null when the task is paused.
Returns the paused task state that can be persisted and restored later.
This method can only be called while the task is paused. The returned state contains
platform-specific resume data and request metadata, but does not include callbacks or abort
signals.
DownloadPauseStateA serializable paused download state.
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 the epoch. Returns a null if the file does not exist, cannot be read or the Android version is earlier than API 26.
Acceptable values are: number | null
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 last modification time of the file expressed in milliseconds since the epoch. Returns a null if the file does not exist, or if it cannot be read.
Acceptable values are: number | null
Deprecated: Use
await file.digest('MD5')instead.
unionA md5 hash of the file. Null if the file does not exist, or it cannot be read.
Acceptable values are: string | null
Deprecated: In favor of
lastModifiedto be more in line with webFile
unionA last modification time of the file expressed in milliseconds since the epoch. Returns a null if the file does not exist, or if it cannot be read.
Acceptable values are: number | null
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.
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 to 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 to the contents of the file as a Uint8Array.
Retrieves byte content of the entire file.
Uint8ArrayThe contents of the file as a Uint8Array.
Determines whether the platform can preview this file.
On iOS, this checks whether Quick Look can preview the file. On Android, this checks whether
an installed app can handle the preview intent for the file's MIME type.
Invalid files and files the app cannot read reject instead of returning false. If the file
does not exist, the promise resolves to false.
Promise<boolean>A promise that resolves to true if the file can be previewed, and false otherwise.
Creates a download task without starting it.
Call downloadAsync() on the returned task to start the download. Use this when you need
pause/resume support, task state, cancellation, or manual progress subscriptions.
DownloadTaskA download task that can be started with downloadAsync().
Example
const destination = new File(Paths.document, 'video.mp4'); const task = File.createDownloadTask('https://example.com/video.mp4', destination, { onProgress: ({ bytesWritten, totalBytes }) => { console.log(`${bytesWritten} / ${totalBytes}`); }, }); const file = await task.downloadAsync();
Creates an upload task for this file without starting it.
Call uploadAsync() on the returned task to start the upload. Use this when you need to
inspect task state, cancel the upload, or subscribe to progress manually.
UploadTaskAn upload task that can be started with uploadAsync().
Example
const file = new File(Paths.document, 'photo.jpg'); const task = file.createUploadTask('https://example.com/upload', { uploadType: UploadType.MULTIPART, onProgress: ({ bytesSent, totalBytes }) => { console.log(`${bytesSent} / ${totalBytes}`); }, }); const result = await task.uploadAsync();
Calculates the digest of the file's contents.
Promise<string>A promise that resolves to the lowercase hexadecimal digest.
Retrieves an object containing properties of a file
FileInfoAn object with file metadata (for example, size, creation date, and so on).
Promise<any>Moves a directory. Updates the uri property that now points to the new location.
Promise<void>Moves a file synchronously. Updates the uri property that now points to the new location.
voidOpens the system file picker for selecting a single file.
This overload requires options.multipleFiles to be undefined or false.
Promise<PickSingleFileResult>Opens the system file picker for selecting multiple files.
This overload requires options.multipleFiles to be true.
Promise<PickMultipleFilesResult>Example
const result = await File.pickFileAsync({ multipleFiles: true, mimeTypes: ['image/*', 'application/pdf'], }); if (!result.canceled) { for (const file of result.result) { console.log(file.uri); } }
Deprecated: Use
pickFileAsync({initialUri, mimeTypes: mimeType})instead.
Opens this file with the platform's file preview flow.
On iOS, this presents Quick Look. On Android, this starts an ACTION_VIEW intent.
The promise resolves once the preview has been presented or handed off to another app.
The promise rejects if the file does not exist or cannot be previewed.
Promise<void>Creates a ReadableStream that reads from this file using a FileHandle internally.
The stream reads in 1024-byte chunks by default. The underlying file handle is closed automatically when the stream is fully consumed or cancelled.
ReadableStream<Uint8Array<ArrayBuffer>>A byte-oriented ReadableStream backed by this file.
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.
BlobReturns a ReadableStream for this file. This is an alias for readableStream()
and implements the Blob.stream() interface.
ReadableStream<Uint8Array<ArrayBuffer>>A byte-oriented ReadableStream backed by this file.
Retrieves text from the file.
Promise<string>A promise that resolves to the contents of the file as string.
Retrieves text from the file.
stringThe contents of the file as string.
Uploads this file to a server and starts the request immediately.
The promise resolves with the HTTP response metadata and body for any completed response, including non-2xx status codes. It is rejected only when the file cannot be read, the request fails, or the upload is cancelled.
Promise<UploadResult>A promise that resolves to the upload result.
Watches this file for changes on the filesystem.
The watcher automatically stops when the file is deleted or renamed. To stop watching manually,
call remove() on the returned subscription.
WatchSubscriptionA subscription handle. Call remove() to stop watching.
Example
const file = new File(Paths.cache, 'data.json'); const subscription = file.watch((event) => { console.log(`File ${event.type}`); }); // Later, stop watching: subscription.remove();
Creates a WritableStream that writes to this file using a FileHandle internally.
The underlying file handle is closed automatically when the stream is closed or aborted.
WritableStream<Uint8Array<ArrayBufferLike>>A WritableStream that accepts Uint8Array chunks.
Type: 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
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.
Checks 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.
Represents an upload task with progress tracking and cancellation support.
Upload tasks start in the idle state. Calling uploadAsync() moves the task to active,
then to completed, cancelled, or error.
UploadTask Properties
UploadTask Methods
Adds a listener for upload progress events.
Note: Prefer the
onProgressoption unless you need manual subscription control.
EventSubscriptionA subscription handle. Call remove() to stop listening.
Cancels the upload operation.
If uploadAsync() is pending, its promise is rejected after the native request is cancelled.
Calling this method after the task reaches completed, cancelled, or error has no effect.
voidReleases the native task handle.
Call this when you no longer need the task and want to release native resources manually.
voidStarts the upload operation.
This method can only be called once, while the task is idle. The promise resolves
with response metadata and body for completed HTTP responses, including non-2xx status codes.
It is rejected when the file cannot be read, the request fails, or the task is cancelled.
If options.signal is aborted, the promise is rejected with an AbortError.
Promise<UploadResult>A promise that resolves to the upload response.
Provides low-level, random-access read and write operations on a file.
Obtain a FileHandle by calling File.open() on a File instance.
The handle maintains an internal byte offset that advances automatically with each
read or write. Set the offset property to seek to an arbitrary position.
Async operations on the same handle are not guaranteed to run in the order they are called.
To ensure ordering, always await async operations on the same handle.
Always call close() when finished to release the underlying file descriptor.
Failing to close a handle may prevent the file from being deleted, moved, or
opened by another process.
Example
import { File, Paths, FileMode } from 'expo-file-system'; const file = new File(Paths.cache, 'data.bin'); const handle = file.open(FileMode.ReadOnly); // Read the first 4 bytes (for example, a magic number) const header = handle.readBytesSync(4); // Seek to byte 100 and read 50 bytes handle.offset = 100; const chunk = await handle.readBytes(50); handle.close();
FileHandle Properties
unionThe current byte offset in the file.
Reading or writing advances the offset by the number of bytes processed. Set this property to seek to an arbitrary position before the next read or write. If set to a value greater than the file size, the next write appends data at the end of the file.
Returns null after the handle has been closed.
Acceptable values are: number | null
FileHandle Methods
Closes the file handle and releases the underlying file descriptor.
After closing, the offset and size properties return null, and any
subsequent call to readBytes, readBytesSync, writeBytes, or
writeBytesSync throws an error.
voidReads up to length bytes from the file starting at the current offset.
The returned Uint8Array may contain fewer than length bytes if the end of the
file is reached. Returns an empty Uint8Array when the offset is already at or
past the end of the file. The offset advances by the number of bytes actually read.
The maximum number of bytes that can be read in a single call is limited by the
platform's ArrayBuffer size: 2 GB (signed 32-bit max) on Android, and the 64-bit
limit on iOS. To read larger files, call this method in a loop.
Promise<Uint8Array<ArrayBuffer>>A promise fulfilled with a Uint8Array containing the bytes read.
Reads up to length bytes from the file starting at the current offset, synchronously.
Behaves identically to readBytes but blocks the JS thread until the data is available.
Uint8Array<ArrayBuffer>A Uint8Array containing the bytes read.
Writes the provided bytes to the file at the current offset, then advances the offset by the number of bytes written.
Promise<void>Methods
Deprecated: Use
new File().copy()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
Promise<void>Deprecated: Import this method from
expo-file-system/legacy. This method will throw in runtime.
anyDeprecated: Import this method from
expo-file-system/legacy. This method will throw in runtime.
anyDeprecated: Use
new File().delete()ornew Directory().delete()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
Promise<void>Deprecated: Use
File.downloadFileAsyncor import this method fromexpo-file-system/legacy. This method will throw in runtime.
Promise<FileSystemDownloadResult>Deprecated: Import this method from
expo-file-system/legacy. This method will throw in runtime.
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.
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.
Promise<void>Deprecated: Use
new File().move()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
Promise<void>Deprecated: Use
new File().text()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
Promise<string>Deprecated: Use
new Directory().list()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
Promise<string[]>Deprecated: Use
@expo/fetchor import this method fromexpo-file-system/legacy. This method will throw in runtime.
Promise<FileSystemUploadResult>Deprecated: Use
await new File().write()ornew File().writeSync()or import this method fromexpo-file-system/legacy. This method will throw in runtime.
Promise<void>Types
Represents the state of a paused download that can be persisted and resumed later.
Literal type: string
Represents the current state of a download task.
Acceptable values are: 'idle' | 'active' | 'paused' | 'completed' | 'cancelled' | 'error'
Literal type: string
Algorithm used to calculate a file digest.
Acceptable values are: 'MD5' | 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512'
Literal type: string
The native URL session mode used by iOS upload and download tasks.
Acceptable values are: 'background' | 'foreground'
Result type for picking multiple files.
Successful picks return { result: File[], canceled: false }. Canceled picks return
{ result: null, canceled: true }.
Type: object shaped as below:
Or object shaped as below:
Result type for picking a single file.
Successful picks return { result: File, canceled: false }. Canceled picks return
{ result: null, canceled: true }.
Type: object shaped as below:
Or object shaped as below:
Type: Exclude<'idle' | 'active' | 'paused' | 'completed' | 'cancelled' | 'error', 'paused'>
Represents the current state of an upload task.
Literal type: string
The type of change that triggered a watcher event.
created— a new file or directory was createdmodified— the file contents or metadata changeddeleted— the file or directory was removedrenamed— the file or directory was renamed or moved
Acceptable values are: 'created' | 'modified' | 'deleted' | 'renamed'
A handle to an active file system watcher. Call remove() to stop watching and release resources.
Enums
Specifies the access mode when opening a file handle.
FileMode.ReadOnly = "r"Opens the file for reading only. The cursor is positioned at the beginning of the file.
FileMode.ReadWrite = "rw"Opens the file for both reading and writing. The cursor is positioned at the beginning of the file.
Note: This mode cannot be used with SAF (Storage Access Framework)
content://URIs.
FileMode.WriteOnly = "w"Opens the file for writing only. The cursor is positioned at the beginning of the file.
FileMode.Append = "wa"Opens the file for writing only. The cursor is positioned at the end of the file.
Note: For SAF files, this is a strict append-only mode. The cursor cannot be moved; calling
seek()will have no effect.