react-native-fs 使用
使用 api 非常简单,可直接参阅 官方文档,这里仅对其路径常量做一个简单解释
android
MainBundlePath: undefined
DocumentDirectoryPath: "/data/user/0/com.project/files"
LibraryDirectoryPath: undefined
CachesDirectoryPath: "/data/user/0/com.project/cache"
TemporaryDirectoryPath: "/data/user/0/com.project/cache"
ExternalDirectoryPath: "/storage/emulated/0/Android/data/com.project/files"
ExternalCachesDirectoryPath: "/storage/emulated/0/Android/data/com.project/cache"
ExternalStorageDirectoryPath: "/storage/emulated/0"
PicturesDirectoryPath: "/storage/emulated/0/Pictures"
FileProtectionKeys: undefined
iOS
MainBundlePath: "/data/Containers/Bundle/Application/E57.../project.app"
DocumentDirectoryPath: "/data/Containers/Data/Application/F18.../Documents"
LibraryDirectoryPath: "/data/Containers/Data/Application/F18.../Library"
CachesDirectoryPath: "/data/Containers/Data/Application/F18.../Library/Caches"
TemporaryDirectoryPath: "/data/Containers/Data/Application/F18.../tmp"
ExternalDirectoryPath: null
ExternalCachesDirectoryPath: undefined
ExternalStorageDirectoryPath: null
PicturesDirectoryPath: undefined
FileProtectionKeys: undefined
MainBundlePath
打包 app 的绝对路径,相当于你可以直接读取 app 内部的一些资源文件,仅在 iOS 下可用,使用的时候要注意拼接路径; android 没这个东西,做双平台的话,应避免使用这个,也没必要,把资源直接打包,也会增加安装包体积
DocumentDirectoryPath
存放 app 使用过程中产生的用户私人文件,可持久化保存,iTunes iCloud 备份/恢复包含此目录,想必 android 应该是同理的
LibraryDirectoryPath
存储配合应用程序的其他非个人文件的数据,比如一些应用程序的配置文件啥的,android 没有这个目录,也应尽量避免使用,当需要存储此类数据,建议放到 CachesDirectoryPath
CachesDirectoryPath
应用程序数据缓存目录,可持久化保存,但可能面临被清除的风险(比如一些清理垃圾文件的操作),所以应用程序如果使用该目录应该做兜底处理
TemporaryDirectoryPath
临时文件目录,这个纯粹是临时的,重启手机,或者文件过多,系统层面就直接清除这个目录,都无需用户去特意触发,用来存放用一下子就仍的文件。 Android 没这个目录,react-native-fs
默认返回了 CachesDirectoryPath
的路径
ExternalDirectoryPath
ExternalStorageDirectoryPath
sd卡目录,仅在 Android 上生效,对应着 DocumentDirectoryPath
、CachesDirectoryPath
,无需申请权限,属于应用专属目录
ExternalStorageDirectoryPath
PicturesDirectoryPath
看路径应该是 android 共享的 sd 卡目录,需要申请权限才能使用,由于是 android only,且需要权限,也建议尽量不使用
FileProtectionKeys
没看到项目中提到,暂且不理会
总结
-
写永久保存的个人文件,用
DocumentDirectoryPath
是最好的,双平台兼容。 -
写缓存文件用
CachesDirectoryPath
最好,也是双平台兼容。 -
写临时文件,iOS 可直接用
TemporaryDirectoryPath
, android 建议使用CachesDirectoryPath
,用完之后手动删除,可将二者封装为一个兼容的函数 -
Android SD 卡,除非是做文件管理相关的应用,不建议使用相关路径,毕竟现在的手机存储空间都比较大,甚至不少手机都取消了 sd 卡