
本文详解如何利用 react-native-fs 在 android/ios 上创建应用专属的持久化文件夹,确保数据在应用卸载重装后仍可保留,并规避系统权限与政策限制。
本文详解如何利用 react-native-fs 在 android/ios 上创建应用专属的持久化文件夹,确保数据在应用卸载重装后仍可保留,并规避系统权限与政策限制。
在 React Native 开发中,开发者常误以为可通过 react-native-fs 直接在设备“根目录”(如 /sdcard/ 或 /)创建全局可见、卸载不丢失的文件夹。但需明确:Android 系统(尤其自 Android 10+ 及 Google Play 政策)严格禁止应用直接写入外部存储根路径,且“内部存储根目录”对第三方应用完全不可访问。真正符合规范、具备跨卸载持久性的方案,是使用 Android 的 App-Specific Directory(应用专属目录),其路径由系统管理,数据在卸载时默认保留(除非用户手动清除或启用 android:fullBackupContent="false")。
✅ 正确路径选择策略
- Android:应使用 RNFS.DownloadDirectoryPath(对应 getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS))或 RNFS.ExternalStorageDirectoryPath(仅限 Android
-
iOS:使用 RNFS.DocumentDirectoryPath(对应 NSDocumentDirectory),该目录受 iCloud 备份保护,且卸载后数据保留(若未启用“iCloud 同步并勾选此目录”则本地保留)。
⚠️ 注意:RNFS.MainBundlePath 和 RNFS.CachesDirectoryPath 不适用——前者只读,后者可能被系统自动清理。
? 实现代码(健壮版)
以下代码封装了路径适配、存在性检查与错误处理,支持生产环境使用:
import { Platform } from 'react-native';
import RNFS from 'react-native-fs';
const FOLDER_NAME = 'MyAppData';
export const createPersistentFolder = async (): Promise<string | null> => {
try {
// 根据平台选择合规的持久化目录
const baseDir =
Platform.OS === 'android'
? RNFS.DownloadDirectoryPath // ✅ Android 推荐:/Android/data/<package>/files/Download/
: RNFS.DocumentDirectoryPath; // ✅ iOS 推荐:Documents/
const folderPath = `${baseDir}/${FOLDER_NAME}`;
// 检查目录是否存在(避免重复创建)
const exists = await RNFS.exists(folderPath);
if (exists) {
console.log(`Persistent folder already exists: ${folderPath}`);
return folderPath;
}
// 创建目录(支持嵌套路径)
await RNFS.mkdir(folderPath);
console.log(`Persistent folder created successfully: ${folderPath}`);
return folderPath;
} catch (error) {
console.error('Failed to create persistent folder:', error);
// 建议在此处触发 Sentry 日志或用户提示
return null;
}
};
// 调用示例
createPersistentFolder().then(path => {
if (path) {
// ✅ 安全写入文件(例如保存 JSON 配置)
RNFS.writeFile(`${path}/config.json`, JSON.stringify({ version: '1.0' }), 'utf8')
.then(() => console.log('Config saved'))
.catch(err => console.error('Write failed:', err));
}
});⚠️ 关键注意事项
-
权限声明(Android):
若使用 DownloadDirectoryPath,无需额外运行时权限(READ_EXTERNAL_STORAGE/WRITE_EXTERNAL_STORAGE 已废弃);但若误用 ExternalStorageDirectoryPath,需动态申请权限且高版本会失败。 -
iOS 文件共享配置:
如需让用户通过 iTunes 或文件 App 访问该文件夹,需在 Info.plist 中添加:<key>UIFileSharingEnabled</key> <true/> <key>LSSupportsOpeningDocumentsInPlace</key> <true/>
-
备份行为控制(Android):
默认情况下,DownloadDirectoryPath 下的数据不会被 Google Backup Service 备份,符合隐私要求;如需备份,请改用 RNFS.ExternalCacheDirectoryPath 并配置 backup_rules.xml。 -
卸载后数据保留逻辑:
DownloadDirectoryPath 和 DocumentDirectoryPath 的数据在用户手动清除应用数据或恢复出厂设置前均保留,但若用户通过“设置 > 应用 > 存储 > 清除数据”操作,则会被删除。
✅ 总结
不要尝试突破系统沙盒去访问“存储根目录”——这既违反政策,又导致兼容性问题。真正的持久化方案是:信任系统提供的 App-Specific 目录,合理选用 DownloadDirectoryPath(Android)或 DocumentDirectoryPath(iOS),配合 RNFS.mkdir() 安全创建子文件夹。该方案零权限依赖、全版本兼容、数据长期可靠,是 React Native 生产级存储的最佳实践。










