react-native-fs-turbo:基于 React Native 鸿蒙生态的文件系统适配项目

基于 JSI 的高性能文件系统访问库

Branch5Tags4
FilesLast commitLast update
19 days ago
19 days ago
19 days ago
19 days ago
19 days ago
19 days ago
19 days ago
19 days ago
1 month ago
19 days ago
1 month ago

react-native-fs-turbo

本项目基于 react-native-fs-turbo开发。如果在使用过程中有任何问题,欢迎在AtomGit提交Issue,会及时跟进。

项目介绍

@hxa-rn/react-native-fs-turbo 是 react-native-fs-turbo 的鸿蒙(OpenHarmony / HarmonyOS)适配包,当前版本 0.6.2。

main 分支适配 React Native 0.82.1、RNOH/CLI 0.82.30、React 19.1.1。

本库含原生 HAR(C++ JSI HostObject + ArkTS 薄 TurboModule),通过 global.RNFSTurboProxy 提供同步文件系统能力:读写、列举、移动/复制、哈希、时间戳、空间查询,以及 11 个沙箱目录 getter。HTTP 下载/上传走 ArkTS(下载 @ohos.request.agent,上传 @ohos.net.http)。业务侧仍 import RNFSTurbo from 'react-native-fs-turbo',公开 JS API 与上游 0.5.1 对齐。

集成指南

npm install @hxa-rn/react-native-fs-turbo

peerDependencies:react-native >= 0.82.1 且 < 0.83,react ^19.1.1。

在工程 harmony.alias 下仍使用原包名导入,不要写成 @hxa-rn/react-native-fs-turbo:

import RNFSTurbo from 'react-native-fs-turbo';

当前版本支持 Autolink(harmony.autolinking:cmakeLibraryTargetName 为 fs_turbo,etsPackageClassName / cppPackageClassName 为 FsTurboPackage)。若工程已接入 RNOH Autolinking,可跳过手动注册。

Autolink 不可用时需同时在 C++ 与 ETS 注册 FsTurboPackage:

  1. 在 entry/oh-package.json5 添加 HAR 依赖并执行 ohpm install。
  2. 在 entry/src/main/cpp/CMakeLists.txt 加入 fs_turbo 子目录并 target_link_libraries。
  3. C++:#include "FsTurboPackage.h",在 getPackages 中 std::make_shared<FsTurboPackage>(ctx)。
  4. ETS:import FsTurboPackage from '@hxa-rn/react-native-fs-turbo',在 createRNPackages 中 new FsTurboPackage(ctx)。

使用说明

文件操作为同步 JSI 调用,用 try/catch 处理错误:

import RNFSTurbo from 'react-native-fs-turbo';

const dir = RNFSTurbo.DocumentDirectoryPath;
const path = `${dir}/hello.txt`;

try {
  RNFSTurbo.writeFile(path, 'Hello HarmonyOS!', 'utf8');
  const text = RNFSTurbo.readFile(path, 'utf8');
  const items = RNFSTurbo.readDir(dir, true);
  console.log(text, items.length);
} catch (err) {
  console.log((err as Error).message);
}

HTTP 下载/上传为异步,jobId 同步返回,可用于中途取消:

const { jobId, promise } = RNFSTurbo.downloadFile({
  fromUrl: 'https://example.com/a.zip',
  toFile: `${RNFSTurbo.DocumentDirectoryPath}/a.zip`,
  connectionTimeout: 2000,
  readTimeout: 2000,
  begin: (res) => console.log(res.statusCode, res.contentLength),
  progress: (res) => console.log(res.bytesWritten, '/', res.contentLength),
});

promise
  .then((res) => console.log('done', res.statusCode, res.bytesWritten))
  .catch((err) => console.log('failed', err));

RNFSTurbo.stopDownload(jobId);

上传示例:

const { jobId, promise } = RNFSTurbo.uploadFiles({
  toUrl: 'https://httpbin.org/post',
  method: 'POST',
  files: [{
    name: 'file',
    filename: 'hello.txt',
    filepath: `${RNFSTurbo.DocumentDirectoryPath}/hello.txt`,
    filetype: 'text/plain',
  }],
});

接口文档

默认导出单例 RNFSTurbo。下列签名来自 src/RNFSTurbo.ts 与 src/Types.ts。

目录 getter

API 功能 鸿蒙取值
MainBundlePath 主包路径 ''(与 Android 空值对齐)
CachesDirectoryPath 缓存目录 cacheDir
DocumentDirectoryPath 文档目录 filesDir
TemporaryDirectoryPath 临时目录 tempDir(无则 cacheDir)
LibraryDirectoryPath 库目录 ''(与 Android 空值对齐)
ExternalDirectoryPath 外部私有目录 降级 filesDir
ExternalStorageDirectoryPath 外部存储根 降级 filesDir
ExternalCachesDirectoryPath 外部缓存 降级 cacheDir
DownloadDirectoryPath 下载目录 降级 filesDir
PicturesDirectoryPath 图片目录 降级 filesDir
RoamingDirectoryPath 漫游目录 ''(与 Android 空值对齐)

同步文件 API

API 功能 参数 / 返回
stat(filepath, isNewFormat?) 元信息 默认旧格式:ctime/mtime 为 Date,isFile/isDirectory 为函数;true 时为秒时间戳与布尔
readDir(dirpath, isNewFormat?) 列举目录项 返回 name/path/size/ctime/mtime/isFile/isDirectory;格式规则同 stat
readdir(dirpath) 文件名列表 返回 string[],不含 . / ..
readFile(filepath, options?) 整文件读取 options 可为编码字符串或对象;utf8/base64/ascii 返回 string,uint8/uint16/uint32/float32 返回 number[]
read(filepath, length, position, options?) 按偏移读取 length/position 为字节;编码规则同 readFile
writeFile(filepath, contents, options?) 写入/覆盖 contents 为 string 或 number[];options 可为编码
appendFile(filepath, contents, options?) 追加写入 同 writeFile
write(filepath, contents, position?, options?) 按偏移写入 position === -1 时追加
moveFile(filepath, destPath, options?) 移动/重命名 鸿蒙上 iOS NSFileProtectionKey 不生效
copyFile(filepath, destPath, options?) 复制单文件 同上
copyFolder(srcFolderPath, destFolderPath, options?) 递归复制目录 同上
unlink(filepath, checkExistence?) 删除文件或目录 默认 checkExistence=true,路径不存在即抛错;false 时不因缺失失败
exists(filepath) 存在性 返回 boolean
hash(filepath, algorithm) 哈希 algorithm:md5/sha1/sha224/sha256/sha384/sha512,返回 hex
touch(filepath, mtime?, ctime?) 修改时间 mtime/ctime 为 Date 或毫秒时间戳;返回秒级 mtime
mkdir(filepath, options?) 递归创建目录 鸿蒙上 iOS 保护选项不生效
getFSInfo() 空间信息 { totalSpace, freeSpace, encryptionEnabled };鸿蒙无 totalSpaceEx/freeSpaceEx

HTTP

API 功能 参数 / 返回
downloadFile(options, complete?, error?) 异步下载 必填 fromUrl、toFile;可选 headers、begin、progress、connectionTimeout、readTimeout(毫秒,0/不传为不超时)。未传 complete 时返回 { jobId, promise }
stopDownload(jobId) 取消下载 错误文案含 downloadFile: Download has been aborted
uploadFiles(options, complete?, error?) 异步上传 必填 toUrl、files;可选 headers、fields、method(POST/PUT)、binaryStreamOnly、begin、progress。公开 API 无超时字段
stopUpload(jobId) 取消上传 错误文案含 uploadFiles: Upload has been aborted

Assets / res(rawfile)

路径相对宿主 HAP resources/rawfile/,可带 rawfile/ 前缀。*Res 与 *Assets 共用同一 rawfile 树。

API 功能
readDirAssets(dirpath, isNewFormat?) 列举 rawfile 目录
readFileAssets(filepath, options?) 读取 rawfile 文件
copyFileAssets(filepath, destPath) 复制 rawfile 到沙箱路径
existsAssets(filepath) 判断 rawfile 是否存在
readFileRes / copyFileRes / existsRes 与 Assets 同一 rawfile 引擎

平台专用(鸿蒙 throw)

公开路径与上游非本平台宏一致,不静默失败:

  • Android:scanFile、getAllExternalFilesDirs → Command only for Android
  • iOS:copyAssetsFileIOS、copyAssetsVideoIOS、pathForGroup、resumeDownload、isResumable、completeHandlerIOS → Command only for iOS

快速验证(运行 Example)

前置条件

依赖 版本要求
Node.js >= 20.19.4
DevEco Studio 支持 API 20 的版本
HarmonyOS SDK 最低兼容 API 17,target API 20

运行步骤

1. 克隆仓库

git clone https://gitcode.com/hxa-rn/react-native-fs-turbo.git
cd react-native-fs-turbo
git checkout main

2. 安装仓库开发依赖

npm install --legacy-peer-deps

3. 进入 example 目录,安装依赖

cd example
npm install --legacy-peer-deps

4. 生成 JS Bundle

npm run dev

产物:harmony/entry/src/main/resources/rawfile/hermes_bundle.hbc

5. 用 DevEco Studio 打开鸿蒙工程

  • 打开 DevEco Studio
  • 选择 example/harmony 目录
  • 等待 Sync 完成

6. 编译并运行 HAP

在 DevEco Studio 中点击运行按钮,将 HAP 安装到设备/模拟器。

注意:Example 中已预置插件依赖和 Package 注册,无需手动配置 Link。

约束与限制

  • 兼容性:React Native 0.82.1、RNOH/CLI 0.82.30、React 19.1.1;Demo 最低兼容 API 17,target API 20;Node.js >= 20.19.4。
  • 权限:库模块 harmony/fs_turbo 声明 ohos.permission.INTERNET,供 downloadFile / uploadFiles 使用。沙箱内文件操作无额外系统权限。
  • 调用方式:文件 API 为同步 JSI,须 try/catch。HTTP 为异步。错误文案前缀为 方法名: 。
  • 沙箱:可写范围为应用 filesDir / cacheDir / tempDir。downloadFile 的 toFile 须位于应用沙箱内,且父目录需已存在。
  • HTTP 超时:connectionTimeout / readTimeout 为毫秒;未传或 0 表示不超时。API 20+ 写入 agent 超时(readTimeout 映射整段 totalTimeout,秒向上取整);更低 API 使用看门狗。discretionary / cacheable / backgroundTimeout / resumable 无鸿蒙等价,不按 iOS/Android 语义生效。
  • AES:默认未编译加密单元,getFSInfo().encryptionEnabled === false;encrypted 读写选项无加密效果。
  • 直调 global.RNFSTurboProxy:downloadFile / uploadFiles / *Assets 的公开入口在 JS/ArkTS,不要绕过 RNFSTurbo 单例去调 C++ stub。

开源license

本项目基于 MIT 协议,详见 LICENSE 文件。

问题反馈渠道

欢迎在 AtomGit 提交 Issue。也可通过 GitCode 仓库与 Issue 反馈:

https://gitcode.com/hxa-rn/react-native-fs-turbo

https://gitcode.com/hxa-rn/react-native-fs-turbo/issues

Introduction

基于 JSI 的高性能文件系统访问库

Customize your domain