Expo FileSystem
提供对设备上本地文件系统的访问的库。
expo-file-system 提供对存储在设备上或作为资源打包到本地项目中的文件和目录的访问。它还允许从网络下载文件。
安装
🌐 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.
应用配置中的配置
🌐 Configuration in app config
如果你在项目中使用配置插件(连续原生生成 (CNG)),可以使用其内置的 配置插件 来配置 expo-file-system。该插件允许你配置无法在运行时设置并且需要构建新的应用二进制文件才能生效的各种属性。如果你的应用不使用 CNG,则需要手动配置该库。
🌐 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
{ "expo": { "plugins": [ [ "expo-file-system", { "supportsOpeningDocumentsInPlace": true, "enableFileSharing": true } ] ] } }
Configurable properties
| Name | Default | Description |
|---|---|---|
supportsOpeningDocumentsInPlace | false | Only for: iOS A boolean to enable |
enableFileSharing | false | Only for: iOS A boolean to enable |
Are you using this library in an existing React Native app?
如果你没有使用连续原生生成(CNG),或者你是手动使用原生 iOS 项目,那么你需要将 LSSupportsOpeningDocumentsInPlace 和 UIFileSharingEnabled 键添加到你项目的 ios/[app]/Info.plist 中:
🌐 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';
File 和 Directory 实例保存对文件、内容或资源 URI 的引用。
🌐 The File and Directory instances hold a reference to a file, content, or asset URI.
文件或目录无需存在——只有在使用错误的类来表示已存在的路径时,构造函数才会抛出错误(例如,如果你尝试创建一个 File 实例,并传入已经存在的目录的路径)。
🌐 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
- 同步和异步,对文件内容的读写访问
- 创建、修改和删除
- 可用属性,如
type、size、creationDate等 - 能够以流的方式或使用
FileHandle类读取和写入文件 - 使用
downloadFileAsync或expo/fetch轻松下载/上传文件
示例
🌐 Examples
写入和读取文本文件
import { File, Paths } from 'expo-file-system'; try { const file = new File(Paths.cache, 'example.txt'); file.create(); // can throw an error if the file already exists or no permission to create it file.write('Hello, world!'); console.log(file.textSync()); // Hello, world! } catch (error) { console.error(error); }
使用系统选择器选择文件
expo-document-picker 的用法:
🌐 Usage with 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 方法:
🌐 Using the built-in pickFileAsync or pickDirectoryAsync method on Android:
import { File } from 'expo-file-system'; try { const file = new File.pickFileAsync(); console.log(file.textSync()); } catch (error) { console.error(error); }
正在下载文件
使用 downloadFileAsync:
🌐 Using 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); // path to the downloaded file, e.g., '${cacheDirectory}/pdfs/sample.pdf' } catch (error) { console.error(error); }
或者使用 expo/fetch:
🌐 Or using 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'); src.write(await response.bytes());
使用 expo/fetch上传文件
你可以使用内置在 Expo 包中的 fetch 直接以 blob 形式上传文件:
🌐 You can upload files as blobs directly with fetch built into the Expo package:
import { fetch } from 'expo/fetch'; import { File, Paths } from 'expo-file-system'; const file = new File(Paths.cache, 'file.txt'); file.write('Hello, world!'); const response = await fetch('https://example.com', { method: 'POST', body: file, });
或者使用 FormData 构造函数:
🌐 Or using the FormData constructor:
import { fetch } from 'expo/fetch'; import { File, Paths } from 'expo-file-system'; const file = new File(Paths.cache, 'file.txt'); 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); }
使用传统文件系统 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
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.
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 epoch. Returns 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 md5 hash of the file. Null if the file does not exist, or it cannot be read.
Acceptable values are: string | null
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: 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.
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 |
|---|---|
| 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.
FileHandleReadableStream<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<ArrayBufferLike>>| Parameter | Type | Description |
|---|---|---|
| content | string | 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.
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.
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. 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>| Parameter | Type | Description |
|---|---|---|
| bytes | Uint8Array | A |
Writes the specified bytes to the file at the current offset.
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
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 URI pointing to the file. This is the same as the |
| 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. |