Reference version

Expo FileSystem iconExpo FileSystem

一个提供访问设备本地文件系统的库。

Android
iOS
tvOS
Included in Expo Go
Bundled version:
~55.0.0

For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.

expo-file-system 提供对存储在设备上或作为资源打包到原生项目中的文件和目录的访问。它还允许从网络下载文件。

安装

Terminal
npx expo install expo-file-system

If you are installing this in an existing React Native app, make sure to install expo in your project.

在应用配置中进行配置

如果你在项目中使用配置插件(Continuous Native Generation (CNG)),你可以使用 expo-file-system 内置的 配置插件 来进行配置。该插件允许你配置运行时无法设置的各种属性,这些属性需要构建新的应用二进制文件后才会生效。如果你的应用使用 CNG,那么你需要手动配置该库。

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-file-system", { "supportsOpeningDocumentsInPlace": true, "enableFileSharing": true } ] ] } }

Configurable properties

NameDefaultDescription
supportsOpeningDocumentsInPlacefalse
Only for:
iOS

一个布尔值,用于在 Info.plist 中启用 LSSupportsOpeningDocumentsInPlace。这允许应用就地打开文档。

enableFileSharingfalse
Only for:
iOS

一个布尔值,用于在 Info.plist 中启用 UIFileSharingEnabled。这会在 iOS Files 应用中启用文件共享,使应用的 Documents 目录可通过 Files 应用、iTunes 文件共享以及其他文件管理工具供用户访问。

Are you using this library in an existing React Native app?

如果你没有使用 Continuous Native Generation(CNG),或者你正在手动使用原生 ios 项目,那么你需要将 LSSupportsOpeningDocumentsInPlaceUIFileSharingEnabled 键添加到项目的 ios/[app]/Info.plist 中:

<key>LSSupportsOpeningDocumentsInPlace</key> <true/> <key>UIFileSharingEnabled</key> <true/>

用法

import { File, Directory, Paths } from 'expo-file-system';

FileDirectory 实例持有对文件、内容或资源 URI 的引用。

文件或目录不需要存在 — 只有在使用了错误的类来表示一个已存在的路径时,构造函数才会抛出错误(例如,如果你尝试创建一个 File 实例,却传入了一个已经存在的目录路径)。

特性

  • 同步和异步的文件内容读写访问
  • 创建、修改和删除
  • 可用属性,例如 typesizecreationDate
  • 能够将文件作为流或使用 FileHandle 类进行读写
  • 使用 downloadFileAsyncexpo/fetch 轻松下载/上传文件

示例

编写和读取文本文件
example.ts
import { File, Paths } from 'expo-file-system'; try { const file = new File(Paths.cache, 'example.txt'); file.create(); // 如果文件已存在或没有创建权限,这里可能会抛出错误 file.write('Hello, world!'); console.log(file.textSync()); // Hello, world! } catch (error) { console.error(error); }
使用系统选择器选择文件

expo-document-picker 配合使用:

example.ts
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 上使用内置的 pickFileAsyncpickDirectoryAsync 方法:

example.ts
import { File } from 'expo-file-system'; try { const file = new File.pickFileAsync(); console.log(file.textSync()); } catch (error) { console.error(error); }
下载文件

使用 downloadFileAsync

example.ts
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

example.ts
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 形式上传文件:

example.ts
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 构造函数:

example.ts
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, });
移动和复制文件
example.ts
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); }
使用旧版 FileSystem API
example.ts
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); }
递归列出目录内容
example.ts
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} 字节)`); } } } try { printDirectory(new Directory(Paths.cache)); } catch (error) { console.error(error); }

API

Classes

Directory

Android
iOS
tvOS

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

exists

Android
iOS
tvOS
Type: boolean

A boolean representing if a directory exists and can be accessed.

size

Android
iOS
tvOS
Literal type: union

A size of the directory in bytes. Null if the directory does not exist, or it cannot be read.

Acceptable values are: number | null

uri

Android
iOS
tvOS
Read Only • Type: string

Represents the directory URI. The field is read-only, but it may change as a result of calling some methods such as move.

name

Android
iOS
tvOS
Type: string

Directory name.

parentDirectory

Android
iOS
tvOS
Type: Directory

Directory containing the file.

Directory Methods

copy(destination)

Android
iOS
tvOS
ParameterType
destinationDirectory | File

Copies a directory.

Returns:
void

create(options)

Android
iOS
tvOS
ParameterType
options(optional)DirectoryCreateOptions

Creates a directory that the current uri points to.

Returns:
void

createDirectory(name)

Android
iOS
tvOS
ParameterType
namestring

Returns:
Directory

createFile(name, mimeType)

Android
iOS
tvOS
ParameterType
namestring
mimeTypestring | null

Returns:
File

delete()

Android
iOS
tvOS

Deletes a directory. Also deletes all files and directories inside the directory.

Returns:
void

info()

Android
iOS
tvOS

Retrieves an object containing properties of a directory.

An object with directory metadata (for example, size, creation date, and so on).

list()

Android
iOS
tvOS

Lists the contents of a directory. Calling this method if the parent directory does not exist will throw an error.

Returns:
(File | Directory)[]

An array of Directory and File instances.

move(destination)

Android
iOS
tvOS
ParameterType
destinationDirectory | File

Moves a directory. Updates the uri property that now points to the new location.

Returns:
void

rename(newName)

Android
iOS
tvOS
ParameterType
newNamestring

Renames a directory.

Returns:
void

File

Android
iOS
tvOS

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

contentUri

Android
Type: string

A content URI to the file that can be shared to external applications.

creationTime

Android
iOS
tvOS
Literal type: union

A 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

exists

Android
iOS
tvOS
Type: boolean

A 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.

md5

Android
iOS
tvOS
Literal type: union

A md5 hash of the file. Null if the file does not exist, or it cannot be read.

Acceptable values are: string | null

modificationTime

Android
iOS
tvOS
Literal type: union

A 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

size

Android
iOS
tvOS
Type: number

A size of the file in bytes. 0 if the file does not exist, or it cannot be read.

type

Android
iOS
tvOS
Type: string

A mime type of the file. An empty string if the file does not exist, or it cannot be read.

uri

Android
iOS
tvOS
Read Only • Type: string

Represents the file URI. The field is read-only, but it may change as a result of calling some methods such as move.

extension

Android
iOS
tvOS
Type: string

File extension.

Example

'.png'

name

Android
iOS
tvOS
Type: string

File name. Includes the extension.

parentDirectory

Android
iOS
tvOS
Type: Directory

Directory containing the file.

File Methods

arrayBuffer()

Android
iOS
tvOS

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.

MDN Reference

base64()

Android
iOS
tvOS

Retrieves content of the file as base64.

Returns:
Promise<string>

A promise that resolves with the contents of the file as a base64 string.

base64Sync()

Android
iOS
tvOS

Retrieves content of the file as base64.

Returns:
string

The contents of the file as a base64 string.

bytes()

Android
iOS
tvOS

Retrieves byte content of the entire file.

A promise that resolves with the contents of the file as a Uint8Array.

bytesSync()

Android
iOS
tvOS

Retrieves byte content of the entire file.

Returns:
Uint8Array

The contents of the file as a Uint8Array.

copy(destination)

Android
iOS
tvOS
ParameterType
destinationDirectory | File

Copies a file.

Returns:
void

create(options)

Android
iOS
tvOS
ParameterType
options(optional)FileCreateOptions

Creates a file.

Returns:
void

delete()

Android
iOS
tvOS

Deletes a file.

Returns:
void

info(options)

Android
iOS
tvOS
ParameterType
options(optional)InfoOptions

Retrieves an object containing properties of a file

Returns:
FileInfo

An object with file metadata (for example, size, creation date, and so on).

move(destination)

Android
iOS
tvOS
ParameterType
destinationDirectory | File

Moves a directory. Updates the uri property that now points to the new location.

Returns:
void

open()

Android
iOS
tvOS

Returns A FileHandle object that can be used to read and write data to the file.

Returns:
FileHandle

readableStream()

Android
iOS
tvOS

rename(newName)

Android
iOS
tvOS
ParameterType
newNamestring

Renames a file.

Returns:
void

slice(start, end, contentType)

Android
iOS
tvOS
ParameterType
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.

MDN Reference

Returns:
Blob

stream()

Android
iOS
tvOS

The stream() method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob.

MDN Reference

text()

Android
iOS
tvOS

Retrieves text from the file.

Returns:
Promise<string>

A promise that resolves with the contents of the file as string.

textSync()

Android
iOS
tvOS

Retrieves text from the file.

Returns:
string

The contents of the file as string.

writableStream()

Android
iOS
tvOS
Returns:
WritableStream<Uint8Array<ArrayBufferLike>>

write(content, options)

Android
iOS
tvOS
ParameterTypeDescription
contentstring | Uint8Array<ArrayBufferLike>

The content to write into the file.

options(optional)FileWriteOptions
-

Writes content to the file.

Returns:
void

Paths

Android
iOS
tvOS

Type: Class extends PathUtilities

Paths Properties

appleSharedContainers

Android
iOS
tvOS
Type: Record<string, Directory>

availableDiskSpace

Android
iOS
tvOS
Type: number

A property that represents the available space on device's internal storage, represented in bytes.

bundle

Android
iOS
tvOS
Type: Directory

A property containing the bundle directory – the directory where assets bundled with the application are stored.

cache

Android
iOS
tvOS
Type: Directory

A property containing the cache directory – a place to store files that can be deleted by the system when the device runs low on storage.

document

Android
iOS
tvOS
Type: Directory

A property containing the document directory – a place to store files that are safe from being deleted by the system.

totalDiskSpace

Android
iOS
tvOS
Type: number

A property that represents the total space on device's internal storage, represented in bytes.

Paths Methods

basename(path, ext)

Android
iOS
tvOS
ParameterTypeDescription
pathstring | File | Directory

The path to get the base name from.

ext(optional)string

An optional file extension.


Returns the base name of a path.

Returns:
string

A string representing the base name.

dirname(path)

Android
iOS
tvOS
ParameterTypeDescription
pathstring | File | Directory

The path to get the directory name from.


Returns the directory name of a path.

Returns:
string

A string representing the directory name.

extname(path)

Android
iOS
tvOS
ParameterTypeDescription
pathstring | File | Directory

The path to get the extension from.


Returns the extension of a path.

Returns:
string

A string representing the extension.

info(...uris)

Android
iOS
tvOS
ParameterType
...urisstring[]

Returns an object that indicates if the specified path represents a directory.

Returns:
PathInfo

isAbsolute(path)

Android
iOS
tvOS
ParameterTypeDescription
pathstring | File | Directory

The path to check.


Checks if a path is absolute.

Returns:
boolean

true if the path is absolute, false otherwise.

join(...paths)

Android
iOS
tvOS
ParameterTypeDescription
...paths(string | File | Directory)[]

An array of path segments.


Joins path segments into a single path.

Returns:
string

A string representing the joined path.

normalize(path)

Android
iOS
tvOS
ParameterTypeDescription
pathstring | File | Directory

The path to normalize.


Normalizes a path.

Returns:
string

A string representing the normalized path.

parse(path)

Android
iOS
tvOS
ParameterTypeDescription
pathstring | File | Directory

The path to parse.


Parses a path into its components.

Returns:
{ base: string, dir: string, ext: string, name: string, root: string }

An object containing the parsed path components.

relative(from, to)

Android
iOS
tvOS
ParameterTypeDescription
fromstring | File | Directory

The base path.

tostring | File | Directory

The relative path.


Resolves a relative path to an absolute path.

Returns:
string

A string representing the resolved path.

FileHandle

Android
iOS
tvOS

FileHandle Properties

offset

Android
iOS
tvOS
Literal type: union

A 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

size

Android
iOS
tvOS
Literal type: union

A size of the file in bytes or null if the file handle is closed.

Acceptable values are: number | null

FileHandle Methods

close()

Android
iOS
tvOS

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.

Returns:
void

readBytes(length)

Android
iOS
tvOS
ParameterTypeDescription
lengthnumber

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.

writeBytes(bytes)

Android
iOS
tvOS
ParameterTypeDescription
bytesUint8Array

A Uint8Array array containing bytes to write.


Writes the specified bytes to the file at the current offset.

Returns:
void

Methods

Deprecated: Use new File().copy() or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.copyAsync(options)

Android
iOS
tvOS
ParameterType
optionsRelocatingOptions

Returns:
Promise<void>

Deprecated: Import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.createDownloadResumable(uri, fileUri, options, callback, resumeData)

Android
iOS
tvOS
ParameterType
uristring
fileUristring
options(optional)DownloadOptions
callback(optional)FileSystemNetworkTaskProgressCallback<DownloadProgressData>
resumeData(optional)string

Returns:
any

Deprecated: Import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.createUploadTask(url, fileUri, options, callback)

Android
iOS
tvOS
ParameterType
urlstring
fileUristring
options(optional)FileSystemUploadOptions
callback(optional)FileSystemNetworkTaskProgressCallback<UploadProgressData>

Returns:
any

Deprecated: Use new File().delete() or new Directory().delete() or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.deleteAsync(fileUri, options)

Android
iOS
tvOS
ParameterType
fileUristring
options(optional)DeletingOptions

Returns:
Promise<void>
Deprecated

FileSystem.deleteLegacyDocumentDirectoryAndroid()

Android
iOS
tvOS
Returns:
Promise<void>

Deprecated: Use File.downloadFileAsync or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.downloadAsync(uri, fileUri, options)

Android
iOS
tvOS
ParameterType
uristring
fileUristring
options(optional)DownloadOptions

Returns:
Promise<FileSystemDownloadResult>

Deprecated: Import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.getContentUriAsync(fileUri)

Android
iOS
tvOS
ParameterType
fileUristring

Returns:
Promise<string>

Deprecated: Use Paths.availableDiskSpace or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.getFreeDiskStorageAsync()

Android
iOS
tvOS
Returns:
Promise<number>

Deprecated: Use new File().info or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.getInfoAsync(fileUri, options)

Android
iOS
tvOS
ParameterType
fileUristring
options(optional)InfoOptions

Returns:
Promise<FileInfo>

Deprecated: Use Paths.totalDiskSpace or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.getTotalDiskCapacityAsync()

Android
iOS
tvOS
Returns:
Promise<number>

Deprecated: Use new Directory().create() or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.makeDirectoryAsync(fileUri, options)

Android
iOS
tvOS
ParameterType
fileUristring
options(optional)MakeDirectoryOptions

Returns:
Promise<void>

Deprecated: Use new File().move() or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.moveAsync(options)

Android
iOS
tvOS
ParameterType
optionsRelocatingOptions

Returns:
Promise<void>

Deprecated: Use new File().text() or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.readAsStringAsync(fileUri, options)

Android
iOS
tvOS
ParameterType
fileUristring
options(optional)ReadingOptions

Returns:
Promise<string>

Deprecated: Use new Directory().list() or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.readDirectoryAsync(fileUri)

Android
iOS
tvOS
ParameterType
fileUristring

Returns:
Promise<string[]>

Deprecated: Use @expo/fetch or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.uploadAsync(url, fileUri, options)

Android
iOS
tvOS
ParameterType
urlstring
fileUristring
options(optional)FileSystemUploadOptions

Returns:
Promise<FileSystemUploadResult>

Deprecated: Use new File().write() or import this method from expo-file-system/legacy. This method will throw in runtime.

FileSystem.writeAsStringAsync(fileUri, contents, options)

Android
iOS
tvOS
ParameterType
fileUristring
contentsstring
options(optional)WritingOptions

Returns:
Promise<void>

Types

DirectoryCreateOptions

Android
iOS
tvOS
PropertyTypeDescription
idempotent(optional)boolean

This flag controls whether the create operation is idempotent (safe to call multiple times without error).

If true, creating a file or directory that already exists will succeed silently. If false, an error will be thrown when the target already exists.

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

DirectoryInfo

Android
iOS
tvOS
PropertyTypeDescription
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.

existsboolean

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 file:// URI pointing to the directory.

DownloadOptions

Android
iOS
tvOS
PropertyTypeDescription
headers(optional)undefined

The headers to send with the request.

idempotent(optional)boolean

This flag controls whether the download operation is idempotent (safe to call multiple times without error).

If true, downloading a file that already exists overwrites the previous one. If false, an error is thrown when the target file already exists.

Default:false

FileCreateOptions

Android
iOS
tvOS
PropertyTypeDescription
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

FileInfo

Android
iOS
tvOS
PropertyTypeDescription
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.

existsboolean

Indicates whether the file exists.

md5(optional)string

Present if the md5 option was truthy. Contains the MD5 hash of the file.

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 fileUri input parameter and preserves its scheme (for example, file:// or content://).

InfoOptions

Android
iOS
tvOS
PropertyTypeDescription
md5(optional)boolean

Whether to return the MD5 hash of the file.

Default:false

PathInfo

Android
iOS
tvOS
PropertyTypeDescription
existsboolean

Indicates whether the path exists. Returns true if it exists; false if the path does not exist or if there is no read permission.

isDirectoryboolean | null

Indicates whether the path is a directory. Returns true or false if the path exists; otherwise, returns null.