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 文件系统
一个提供对设备本地文件系统访问的库。
expo-file-system 提供了对存储在设备上或作为资源打包进原生项目中的文件和目录的访问。它还允许从网络下载文件。
安装
- npx expo install expo-file-systemIf you are installing this in an existing React Native app, make sure to install expo in your project.
app 配置中的配置
如果你在项目中使用配置插件(Continuous Native Generation (CNG)),你可以使用 expo-file-system 内置的 config plugin 来进行配置。该插件允许你配置各种无法在运行时设置的属性,并且这些设置需要构建新的应用二进制文件后才会生效。如果你的应用不使用 CNG,那么你需要手动配置该库。
Example app.json with config plugin
{ "expo": { "plugins": [ [ "expo-file-system", { "supportsOpeningDocumentsInPlace": true, "enableFileSharing": true } ] ] } }
Configurable properties
| Name | Default | Description |
|---|---|---|
supportsOpeningDocumentsInPlace | false | Only for: iOS 一个布尔值,用于在 Info.plist 中启用 |
enableFileSharing | false | Only for: iOS 一个布尔值,用于在 Info.plist 中启用 |
Are you using this library in an existing React Native app?
如果你没有使用 Continuous Native Generation(CNG),或者你正在手动使用原生 ios 项目,那么你需要将 LSSupportsOpeningDocumentsInPlace 和 UIFileSharingEnabled 键添加到项目的 ios/[app]/Info.plist 中:
<key>LSSupportsOpeningDocumentsInPlace</key> <true/> <key>UIFileSharingEnabled</key> <true/>
用法
import { File, Directory, Paths } from 'expo-file-system';
File 和 Directory 实例持有对文件、内容或资源 URI 的引用。
文件或目录不需要存在——只有当使用了错误的类来表示一个已存在的路径时,构造函数才会抛出错误(例如,如果你尝试创建一个 File 实例,但传入的路径实际上是一个已经存在的目录)。
特性
- 同步和异步的文件内容读写访问
- 创建、修改和删除
- 可用属性,例如
type、size、creationDate等更多属性 - 能够使用流或
FileHandle类读取和写入文件 - 使用
downloadFileAsync或expo/fetch轻松下载/上传文件 - 使用平台原生流程预览文件
示例
写入和读取文本文件
import { File, Paths } from 'expo-file-system'; try { const file = new File(Paths.cache, 'example.txt'); file.create(); // 如果文件已存在或没有创建权限,可能会抛出错误 await file.write('Hello, world!'); // 也可以使用 `file.writeSync('Hello, world!');` 进行同步调用 console.log(file.textSync()); // Hello, world! } catch (error) { console.error(error); }
使用系统选择器选择文件
与 expo-document-picker 一起使用:
import { File } from 'expo-file-system'; import * as DocumentPicker from 'expo-document-picker'; try { const result = await DocumentPicker.getDocumentAsync({ copyToCacheDirectory: true }); if (!result.canceled) { const { uri } = result.assets[0]; const file = new File(uri); console.log(file.textSync()); } } catch (error) { console.error(error); }
在 Android 上使用内置的 pickFileAsync 或 pickDirectoryAsync 方法:
import { File } from 'expo-file-system'; try { const file = new File.pickFileAsync(); console.log(file.textSync()); } catch (error) { console.error(error); }
下载文件
使用 downloadFileAsync:
import { Directory, File, Paths } from 'expo-file-system'; const url = 'https://pdfobject.com/pdf/sample.pdf'; const destination = new Directory(Paths.cache, 'pdfs'); try { destination.create(); const output = await File.downloadFileAsync(url, destination); console.log(output.exists); // true console.log(output.uri); // 下载文件的路径,例如 '${cacheDirectory}/pdfs/sample.pdf' } catch (error) { console.error(error); }
或者使用 expo/fetch:
import { fetch } from 'expo/fetch'; import { File, Paths } from 'expo-file-system'; const url = 'https://pdfobject.com/pdf/sample.pdf'; const response = await fetch(url); const src = new File(Paths.cache, 'file.pdf'); await src.write(await response.bytes());
预览文件
使用 File.preview() 通过平台的文件预览流程打开本地文件。文件预览目前支持 Android 和 iOS。在 iOS 上,这会展示 Quick Look,它支持许多常见文件类型,例如 PDF、图片、文本文件、CSV 文件和 Office 文档。在 Android 上,这会打开一个 ACTION_VIEW intent,因此支持情况取决于设备上已安装且能够处理该文件 MIME 类型的应用。
import { File, Paths } from 'expo-file-system'; const file = await File.downloadFileAsync( 'https://pdfobject.com/pdf/sample.pdf', new File(Paths.cache, 'sample.pdf') ); if (await file.canPreview()) { await file.preview({ title: 'Sample PDF' }); }
mimeType 选项默认使用文件的 type 属性。如果文件扩展名未能正确识别类型,请显式传入 mimeType,尤其是在 Android 上,因为 MIME 类型会用于查找兼容的应用。当 Android 无法解析 MIME 类型时,canPreview() 会解析为 false,并且 preview() 会拒绝。
如果文件无效或无法读取,canPreview() 会拒绝。当文件不存在或平台无法预览时,它会解析为 false。
preview() 会在原生预览已展示或已交由其他应用处理后解析完成。如果文件不存在、无法读取或没有可用预览,它会拒绝。它不会等待用户关闭查看器。
如果你的应用中分享面板很有用,那么在预览失败时,你可以结合使用 expo-sharing:
import { File, Paths } from 'expo-file-system'; import * as Sharing from 'expo-sharing'; // 这里可以是之前创建、选择或下载的文件。 const file = new File(Paths.cache, 'report.pdf'); try { await file.preview({ title: 'Report' }); } catch { if (await Sharing.isAvailableAsync()) { await Sharing.shareAsync(file.uri, { dialogTitle: 'Share report', mimeType: file.type || 'application/pdf', }); } }
使用 expo/fetch 上传文件
你可以直接使用 Expo 包内置的 fetch 将文件作为 blob 上传:
import { fetch } from 'expo/fetch'; import { File, Paths } from 'expo-file-system'; const file = new File(Paths.cache, 'file.txt'); await file.write('Hello, world!'); const response = await fetch('https://example.com', { method: 'POST', body: file, });
或者使用 FormData 构造函数:
import { fetch } from 'expo/fetch'; import { File, Paths } from 'expo-file-system'; const file = new File(Paths.cache, 'file.txt'); await file.write('Hello, world!'); const formData = new FormData(); formData.append('data', file); const response = await fetch('https://example.com', { method: 'POST', body: formData, });
移动和复制文件
import { Directory, File, Paths } from 'expo-file-system'; try { const file = new File(Paths.document, 'example.txt'); file.create(); console.log(file.uri); // '${documentDirectory}/example.txt' const copiedFile = new File(Paths.cache, 'example-copy.txt'); file.copy(copiedFile); console.log(copiedFile.uri); // '${cacheDirectory}/example-copy.txt' file.move(Paths.cache); console.log(file.uri); // '${cacheDirectory}/example.txt' file.move(new Directory(Paths.cache, 'newFolder')); console.log(file.uri); // '${cacheDirectory}/newFolder/example.txt' } catch (error) { console.error(error); }
使用 FileHandle 进行随机访问读取
使用 FileHandle 可以高效地随机访问读取大文件,而无需将整个文件加载到内存中。通过调用 file.open() 获取句柄,使用 offset 属性可在任意位置进行读写,完成后务必关闭句柄。
import { File, Paths, FileMode } from 'expo-file-system'; const file = new File(Paths.document, 'recording.wav'); const handle = file.open(FileMode.ReadOnly); // 读取 WAV 头部(前 44 字节) const header = handle.readBytesSync(44); const sampleRate = new DataView(header.buffer).getUint32(24, true); console.log(`Sample rate: ${sampleRate} Hz`); // 移动到特定偏移并读取一个数据块 handle.offset = 1024; const chunk = await handle.readBytes(4096); console.log(`从偏移 1024 读取了 ${chunk.length} 字节`); // 以 64 KB 的块读取整个文件 handle.offset = 0; const CHUNK_SIZE = 64 * 1024; while (handle.offset! < handle.size!) { const data = await handle.readBytes(CHUNK_SIZE); // 处理数据... } handle.close();
使用旧版 FileSystem API
import * as FileSystem from 'expo-file-system/legacy'; import { File, Paths } from 'expo-file-system'; try { const file = new File(Paths.cache, 'example.txt'); const content = await FileSystem.readAsStringAsync(file.uri); console.log(content); } catch (error) { console.error(error); }
递归列出目录内容
import { Directory, Paths } from 'expo-file-system'; function printDirectory(directory: Directory, indent: number = 0) { console.log(`${' '.repeat(indent)} + ${directory.name}`); const contents = directory.list(); for (const item of contents) { if (item instanceof Directory) { printDirectory(item, indent + 2); } else { console.log(`${' '.repeat(indent + 2)} - ${item.name} (${item.size} bytes)`); } } } try { printDirectory(new Directory(Paths.cache)); } catch (error) { console.error(error); }
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
| Parameter | Type |
|---|---|
| destination | File | Directory |
| options(optional) | RelocationOptions |
Copies a directory.
Promise<void>| Parameter | Type |
|---|---|
| destination | File | Directory |
| options(optional) | RelocationOptions |
Copies a directory synchronously.
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).
| Parameter | Type |
|---|---|
| destination | File | Directory |
| options(optional) | RelocationOptions |
Moves a directory. Updates the uri property that now points to the new location.
Promise<void>| Parameter | Type |
|---|---|
| destination | File | Directory |
| options(optional) | RelocationOptions |
Moves a directory synchronously. Updates the uri property that now points to the new location.
void| Parameter | Type | Description |
|---|---|---|
| callback | (event: WatchEvent<File | Directory>) => void | Invoked when a change is detected. Receives a |
| options(optional) | WatchOptions | Configuration for debouncing and filtering events. |
Watches 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
| Parameter | Type | Description |
|---|---|---|
| eventName | 'progress' | The event to listen to. Only |
| listener | (data: DownloadProgress) => void | Invoked with download progress updates. |
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.
| Parameter | Type | Description |
|---|---|---|
| state | DownloadPauseState | The saved pause state. |
| options(optional) | DownloadTaskOptions | Optional download task options to attach to the restored task. |
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
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.
| Parameter | Type | Description |
|---|---|---|
| options(optional) | FileCanPreviewOptions | Preview options. |
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.
| Parameter | Type |
|---|---|
| destination | File | Directory |
| options(optional) | RelocationOptions |
Copies a file.
Promise<void>| Parameter | Type |
|---|---|
| destination | File | Directory |
| options(optional) | RelocationOptions |
Copies a file synchronously.
void| Parameter | Type | Description |
|---|---|---|
| url | string | The URL of the file to download. |
| destination | File | Directory | The destination file or directory. If a directory is provided, the resulting filename is determined from the response headers or URL. |
| options(optional) | DownloadTaskOptions | Download task options. |
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();
| Parameter | Type | Description |
|---|---|---|
| url | string | The URL to upload the file to. |
| options(optional) | UploadOptions | Upload options. |
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();
| 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).
Promise<any>| Parameter | Type |
|---|---|
| destination | File | Directory |
| options(optional) | RelocationOptions |
Moves a directory. Updates the uri property that now points to the new location.
Promise<void>| Parameter | Type |
|---|---|
| destination | File | Directory |
| options(optional) | RelocationOptions |
Moves a file synchronously. Updates the uri property that now points to the new location.
void| Parameter | Type | Description |
|---|---|---|
| mode(optional) | FileMode | The
|
Returns A FileHandle object that can be used to read and write data to the file.
FileHandle| Parameter | Type | Description |
|---|---|---|
| options(optional) | PickSingleFileOptions | File picker options. |
Opens the system file picker for selecting a single file.
This overload requires options.multipleFiles to be undefined or false.
Promise<PickSingleFileResult>| Parameter | Type | Description |
|---|---|---|
| options(optional) | PickMultipleFilesOptions | File picker options. |
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.
| 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. |
| Parameter | Type | Description |
|---|---|---|
| options(optional) | FilePreviewOptions | Preview options. |
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.
| 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.
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.
| Parameter | Type | Description |
|---|---|---|
| url | string | The URL to upload the file to. |
| options(optional) | UploadOptions | Upload options. |
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.
| Parameter | Type | Description |
|---|---|---|
| callback | (event: WatchEvent<File>) => void | Invoked when a change is detected. Receives a |
| options(optional) | WatchOptions | Configuration for debouncing and filtering events. |
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.
| Parameter | Type | Description |
|---|---|---|
| content | string | ArrayBuffer | Uint8Array<ArrayBufferLike> | The content to write into the file. |
| options(optional) | FileWriteOptions | - |
Writes content to the file.
Promise<void>| Parameter | Type | Description |
|---|---|---|
| content | string | ArrayBuffer | Uint8Array<ArrayBufferLike> | The content to write into the file. |
| options(optional) | FileWriteOptions | - |
Writes content to the file.
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.
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
| Parameter | Type | Description |
|---|---|---|
| eventName | 'progress' | The event to listen to. Only |
| listener | (data: UploadProgress) => void | Invoked with upload progress updates. |
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.
void| Parameter | Type | Description |
|---|---|---|
| length | number | The number of bytes to read. |
Reads 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.
| Parameter | Type | Description |
|---|---|---|
| length | number | The number of bytes to 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.
| Parameter | Type | Description |
|---|---|---|
| bytes | Uint8Array | A |
Writes the provided bytes to the file at the current offset, then advances the offset by the number of bytes written.
Promise<void>| Parameter | Type | Description |
|---|---|---|
| bytes | Uint8Array | A |
Writes the provided bytes to the file at the current offset synchronously, then advances the offset by the number of bytes written.
voidMethods
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
await new File().write()ornew File().writeSync()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 |
| onProgress(optional) | (data: DownloadProgress) => void | A callback that is invoked with progress updates during the download. |
| signal(optional) | AbortSignal | An |
Represents the state of a paused download that can be persisted and resumed later.
| Property | Type | Description |
|---|---|---|
| fileUri | string | The destination file or directory URI. |
| headers(optional) | Record<string, string> | Custom headers that were used for the download request. |
| isDirectory | boolean | Whether the destination is a directory. When |
| resumeData(optional) | string | Platform-specific opaque resume data. |
| url | string | The URL of the download. |
Data provided to the onProgress callback during a file download.
| Property | Type | Description |
|---|---|---|
| bytesWritten | number | The number of bytes written so far. |
| totalBytes | number | The total number of bytes expected to be downloaded. |
Options for download task operations.
| Property | Type | Description |
|---|---|---|
| headers(optional) | Record<string, string> | Custom headers to include in the request. |
| onProgress(optional) | (data: DownloadProgress) => void | Callback for download progress updates. |
| sessionType(optional) | NetworkTaskSessionType | Only for: iOS Determines whether the iOS native session should continue in the background. Android accepts this option for API consistency and ignores it. When set to Default: 'background' |
| signal(optional) | AbortSignal | AbortSignal to cancel the download. |
Literal type: string
Represents the current state of a download task.
Acceptable values are: 'idle' | 'active' | 'paused' | 'completed' | 'cancelled' | 'error'
| Property | Type | Description |
|---|---|---|
| mimeType(optional) | string | MIME type of the file. Android uses this value to find a matching app for the preview intent.
If omitted, the MIME type defaults to the file's |
| 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 URI pointing to the file. This is the same as the |
| Property | Type | Description |
|---|---|---|
| mimeType(optional) | string | MIME type of the file. Android uses this value to find a matching app for the preview intent.
If omitted, the MIME type defaults to the file's |
| title(optional) | string | Optional display title for the preview when the platform supports one. |
| Property | Type | Description |
|---|---|---|
| append(optional) | boolean | Whether to append the contents to the end of the file or overwrite the existing file. Default: false |
| encoding(optional) | EncodingType | 'utf8' | 'base64' | The encoding format to use when writing the file. Default: FileSystem.EncodingType.UTF8 |
| Property | Type | Description |
|---|---|---|
| md5(optional) | boolean | Whether to return the MD5 hash of the file. Default: false |
Literal type: string
The native URL session mode used by iOS upload and download tasks.
Acceptable values are: 'background' | 'foreground'
| 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. |
Shared options accepted by file picker calls.
| Property | Type | Description |
|---|---|---|
| initialUri(optional) | string | A URI pointing to an initial folder in which the file picker is opened. |
| mimeTypes(optional) | string | string[] | The MIME type(s) of the documents that are available
to be picked. It also supports wildcards like Default: '*/*' |
| multipleFiles(optional) | boolean | Allows multiple files to be selected from the system UI. Default: false |
Options for picking multiple files.
Type: PickFileGeneralOptions extended by:
| Property | Type | Description |
|---|---|---|
| multipleFiles | true | Allows multiple files to be selected from the system UI. |
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:
| Property | Type | Description |
|---|---|---|
| canceled | false | Indicates that the picker completed with selected files. |
| result | File[] | The selected files. |
Or object shaped as below:
| Property | Type | Description |
|---|---|---|
| canceled | true | Indicates that the user canceled the picker without selecting files. |
| result | null | Always |
Options for picking a single file.
Type: PickFileGeneralOptions extended by:
| Property | Type | Description |
|---|---|---|
| multipleFiles(optional) | false | Keeps the picker in single-file mode. Omit this property or set it to Default: false |
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:
| Property | Type | Description |
|---|---|---|
| canceled | false | Indicates that the picker completed with a selected file. |
| result | File | The selected file. |
Or object shaped as below:
| Property | Type | Description |
|---|---|---|
| canceled | true | Indicates that the user canceled the picker without selecting files. |
| result | null | Always |
Options for moving or copying files and directories.
| Property | Type | Description |
|---|---|---|
| overwrite(optional) | boolean | Whether to overwrite the destination if it exists. Default: false |
Options for upload operations.
| Property | Type | Description |
|---|---|---|
| fieldName(optional) | string | The field name for the file in multipart uploads. Default: 'file' |
| headers(optional) | Record<string, string> | Custom headers to include in the request. |
| httpMethod(optional) | 'POST' | 'PUT' | 'PATCH' | The HTTP method to use. Default: 'POST' |
| mimeType(optional) | string | The MIME type of the file. |
| onProgress(optional) | (data: UploadProgress) => void | Callback for upload progress updates.
|
| parameters(optional) | Record<string, string> | Additional form parameters to include in multipart uploads. |
| sessionType(optional) | NetworkTaskSessionType | Only for: iOS Determines whether the iOS native session should continue in the background. When set to Default: 'background' |
| signal(optional) | AbortSignal | An |
| uploadType(optional) | UploadType | The type of upload operation. Default: UploadType.BINARY_CONTENT |
Represents upload progress data.
| Property | Type | Description |
|---|---|---|
| bytesSent | number | The number of bytes sent so far. |
| totalBytes | number | The total number of bytes to send. |
Represents the result of an upload operation.
| Property | Type | Description |
|---|---|---|
| body | string | The response body as a string. |
| headers | Record<string, string> | The response headers. |
| status | number | The HTTP status code. |
Type: Exclude<'idle' | 'active' | 'paused' | 'completed' | 'cancelled' | 'error', 'paused'>
Represents the current state of an upload task.
Describes a change detected by a file system watcher.
| Property | Type | Description |
|---|---|---|
| nativeEventFlags(optional) | number | Raw platform-specific event flags for advanced use cases. On Android: FileObserver event flags. On iOS: DispatchSource.FileSystemEvent flags. |
| newTarget(optional) | T | Only for: Android For rename events, the new path after rename. Populated when MOVED_FROM and MOVED_TO events are correlated within the debounce window. |
| target | T | The file or directory that changed. For |
| type | WatchEventType | The kind of change that occurred. |
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'
Options for configuring a file system watcher.
| Property | Type | Description |
|---|---|---|
| debounce(optional) | number | The debounce interval in milliseconds for coalescing rapid successive events into a single callback. Default: 100 |
| events(optional) | WatchEventType[] | Limits which event types trigger the callback. If omitted, all event types are observed. On iOS, directory watchers only provide coarse-grained notifications that the directory itself
changed, so filtering for child-level |
A handle to an active file system watcher. Call remove() to stop watching and release resources.
| Property | Type | Description |
|---|---|---|
| remove | () => void | Stops watching for changes and releases native resources. After calling this method, the callback will no longer be invoked. |
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.