Expo FileSystem(next)
一个提供对设备本地文件系统访问的库。
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
信息
expo-file-system库中包含next版本的 FileSystem API。它可以与之前的 API 一起使用,并提供一种简化的、面向对象的文件系统操作方式。
重要 为了提供更快的更新,
expo-file-system/next目前在 Expo Go 和 Snack 中不受支持。要使用它,请创建一个开发构建。
expo-file-system/next 提供对存储在设备本地的文件系统的访问。它还可以从网络下载文件。
安装
- npx expo install expo-file-systemIf you are installing this in an existing React Native app, make sure to install expo in your project.
用法
写入和读取文本文件
import { File, Paths } from 'expo-file-system/next'; try { const file = new File(Paths.cache, 'example.txt'); file.create(); // 如果文件已存在或没有创建权限,这里可能会抛出错误 file.write('Hello, world!'); console.log(file.text()); // 你好,世界! } catch (error) { console.error(error); }
下载文件
使用 downloadFileAsync:
import { Directory, File, Paths } from 'expo-file-system/next'; 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/next'; 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 上传:
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 构造函数:
import { fetch } from 'expo/fetch'; import { File, Paths } from 'expo-file-system/next'; const src = 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/next'; 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); }
使用旧版 FileSystem API
import * as FileSystem from 'expo-file-system'; import { File, Paths } from 'expo-file-system/next'; 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/next'; 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} 字节)`); } } } 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.
Directory Properties
booleanA boolean representing if a directory exists. true if the directory exists, false otherwise.
Also, false if the application does not have read access to the file.
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) | CreateOptions |
Creates a directory that the current uri points to.
voidDeletes a directory. Also deletes all files and directories inside the directory.
voidType: Class extends FileSystemFile
File Properties
booleanA boolean representing if a file exists. true if the file exists, false otherwise.
Also, false if the application does not have read access to the file.
unionA md5 hash of the file. Null if the file does not exist, or it cannot be read.
Acceptable values are: null | string
unionA size of the file in bytes. Null if the file does not exist, or it cannot be read.
Acceptable values are: null | number
unionA mime type of the file. Null if the file does not exist, or it cannot be read.
Acceptable values are: null | string
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
Retrieves content of the file as base64.
stringThe contents of the file as a base64 string.
Returns the file as a Blob. The blob can be used in @expo/fetch to send files over network and for other uses.
BlobRetrieves byte content of the entire file.
Uint8ArrayThe contents of the file as a Uint8Array.
| Parameter | Type | Description |
|---|---|---|
| url | string | The URL of the file to download. |
| destination | Directory | File | The destination directory or file. If a directory is provided, the resulting filename will be determined based on the response headers. |
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>WritableStream<Uint8Array>| Parameter | Type | Description |
|---|---|---|
| content | string | Uint8Array | The content to write into the file. |
Writes content to the file.
voidFileHandle Properties
unionA property that indicates the current byte offset in the file. Calling readBytes or writeBytes will read or write a specified amount of bytes starting from this offset. The offset is incremented by the number of bytes read or written.
The offset can be set to any value within the file size. If the offset is set to a value greater than the file size, the next write operation will append data to the end of the file.
Null if the file handle is closed.
Acceptable values are: null | number
FileHandle Methods
Closes the file handle. This allows the file to be deleted, moved or read by a different process. Subsequent calls to readBytes or writeBytes will throw an error.
void| Parameter | Type | Description |
|---|---|---|
| length | number | The number of bytes to read. |
Reads the specified amount of bytes from the file at the current offset.
Uint8Array| Parameter | Type | Description |
|---|---|---|
| bytes | Uint8Array | A |
Writes the specified bytes to the file at the current offset.
voidType: Class extends PathUtilities
Paths Properties
Record<string, Directory>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.
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.