This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo 文件系统
一个提供访问设备本地文件系统的库。
expo-file-system 提供对存储在设备上的文件和目录,或作为资源打包进原生项目中的文件和目录的访问。它还允许从网络下载文件。
安装
If you are installing this in an existing React Native app, make sure to install expo in your project.
在 app 配置中进行配置
如果你在项目中使用 config plugins(Continuous Native Generation (CNG)),可以使用 expo-file-system 内置的 config plugin 来进行配置。该插件允许你配置各种无法在运行时设置的属性,这些属性需要构建新的应用二进制文件后才会生效。如果你的应用不使用 CNG,那么你需要手动配置该库。
Example app.json with config plugin
Configurable properties
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轻松下载/上传文件
示例
使用系统选择器选择文件
与 expo-document-picker 一起使用:
在 Android 上使用内置的 pickFileAsync 或 pickDirectoryAsync 方法:
API
Constants
Type: '100'
The default debounce time for file system watcher events in milliseconds.
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();
Type: Class extends FileSystemDownloadTask
Represents a download task with pause/resume support and progress tracking.
DownloadTask Properties
DownloadTask Methods
Adds a listener for the given event name.
EventSubscriptionSynchronously calls all the listeners attached to that specific event. The event can include any number of arguments that will be passed to the listeners.
voidReturns a number of listeners added to the given event.
numberPromise<void>A function that detaches the JS and native objects to let the native object deallocate before the JS object gets deallocated by the JS garbage collector. Any subsequent calls to native functions of the object will throw an error as it is no longer associated with its native counterpart.
In most cases, you should never need to use this function, except some specific performance-critical cases when
manual memory management makes sense and the native object is known to exclusively retain some native memory
(such as binary data or image bitmap). Before calling this function, you should ensure that nothing else will use
this object later on. Shared objects created by React hooks are usually automatically released in the effect's cleanup phase,
for example: useVideoPlayer() from expo-video and useImage() from expo-image.
voidRemoves all listeners for the given event name.
voidRemoves a listener for the given event name.
voidDownloadPauseStateFunction that is automatically invoked when the first listener for an event with the given name is added. Override it in a subclass to perform some additional setup once the event started being observed.
voidType: 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 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.
Creates a download task for downloading a file with pause/resume support.
DownloadTaskA DownloadTask instance that can be used to control the download.
Example
const dest = new File(Paths.document, 'video.mp4'); const downloadTask = File.createDownloadTask(url, dest, { onProgress: ({ bytesWritten, totalBytes }) => { console.log(`Downloaded ${bytesWritten} of ${totalBytes} bytes`); } }); const file = await downloadTask.downloadAsync();
Creates an upload task for uploading this file with progress tracking.
UploadTaskAn UploadTask instance that can be used to control the upload.
Example
const file = new File(Paths.document, 'photo.jpg'); const uploadTask = file.createUploadTask(url, { uploadType: UploadType.MULTIPART, headers: { Authorization: 'Bearer token' }, onProgress: ({ bytesSent, totalBytes }) => { console.log(`Uploaded ${bytesSent} of ${totalBytes} bytes`); } }); const result = await uploadTask.uploadAsync(); console.log('Upload status:', result.status);
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.
Promise<void>Moves a file synchronously. Updates the uri property that now points to the new location.
voidAn overload of the pickFileAsync method, which picks and returns a single File.
This overload requires options to have multipleFiles flag be undefined or false.
Promise<PickSingleFileResult>An overload of the pickFileAsync method, which picks and returns a list of File's.
This overload requires options to have multipleFiles flag be true.
Promise<PickMultipleFilesResult>Deprecated: Use
pickFileAsync({initialUri, mimeTypes: mimeType})instead.
ReadableStream<Uint8Array<ArrayBuffer>>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.
Uploads this file to the network.
The promise resolves with the HTTP response metadata and body for any completed response, including non-2xx status codes. It rejects only for local file errors, transport failures, or cancellation.
Promise<UploadResult>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();
WritableStream<Uint8Array<ArrayBufferLike>>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.
Type: Class extends FileSystemUploadTask
Represents an upload task with progress tracking and cancellation support.
UploadTask Properties
UploadTaskStateUploadTask Methods
Adds a listener for the given event name.
EventSubscriptionSynchronously calls all the listeners attached to that specific event. The event can include any number of arguments that will be passed to the listeners.
voidReturns a number of listeners added to the given event.
numberA function that detaches the JS and native objects to let the native object deallocate before the JS object gets deallocated by the JS garbage collector. Any subsequent calls to native functions of the object will throw an error as it is no longer associated with its native counterpart.
In most cases, you should never need to use this function, except some specific performance-critical cases when
manual memory management makes sense and the native object is known to exclusively retain some native memory
(such as binary data or image bitmap). Before calling this function, you should ensure that nothing else will use
this object later on. Shared objects created by React hooks are usually automatically released in the effect's cleanup phase,
for example: useVideoPlayer() from expo-video and useImage() from expo-image.
voidRemoves all listeners for the given event name.
voidRemoves a listener for the given event name.
voidFunction that is automatically invoked when the first listener for an event with the given name is added. Override it in a subclass to perform some additional setup once the event started being observed.
voidFunction that is automatically invoked when the last listener for an event with the given name is removed. Override it in a subclass to perform some additional cleanup once the event is no longer observed.
voidPromise<UploadResult>FileHandle 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: number | null
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.
voidReads the specified amount of bytes from the file at the current offset. Max amount of bytes read at once is capped by ArrayBuffer max size (32 bit signed MAX_INT on Android and 64 bit on iOS), but you can read from a FileHandle multiple times.
Uint8Array<ArrayBuffer>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
new File().write()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
The native URL session mode used by iOS upload and download tasks.
Acceptable values are: 'background' | 'foreground'
Literal type: union
Result type for picking multiple files.
Acceptable values are: PickMultipleFilesSuccessResult | PickFileCanceledResult
Literal type: union
Result type for picking a single file.
Acceptable values are: PickSingleFileSuccessResult | PickFileCanceledResult
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.