模板版本:v0.4.0

react-native-fs

本项目基于 react-native-fs 开发。

该第三方库的仓库已迁移至 Gitcode,且支持直接从 npm 下载,新的包名为:@react-native-ohos/react-native-fs,具体版本所属关系如下:

三方库名称 三方库版本 发布信息 支持RN版本 Autolink 编译API版本 社区基线版本 npm地址
@react-native-ohos/react-native-fs ~2.22.0 Gitcode Releases 0.82.* API12+ 2.20.0 Npm Address
@react-native-ohos/react-native-fs ~2.21.0 Gitcode Releases 0.77.* API12+ 2.20.0 Npm Address
@react-native-ohos/react-native-fs ~2.20.1 Gitcode Releases 0.72.* API12+ 2.20.0 Npm Address
@react-native-oh-tpl/react-native-fs <= 2.20.0-0.1.14@deprecated Github Releases(deprecated) 0.72.* API12+ 2.20.0 Npm Address

1. 安装与使用

进入到工程目录并输入以下命令:

npm

npm install @react-native-ohos/react-native-fs

yarn

yarn add @react-native-ohos/react-native-fs

下面的代码展示了这个库的基本使用场景:

使用时 import 的库名不变。

import React, { useState } from "react";
import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, TextInput, Button } from "react-native";
import FS from "react-native-fs";
import { Colors } from "react-native/Libraries/NewAppScreen";

function App(): React.JSX.Element {
  const [mkdirParam, setMkdirParam] = useState("");
  const mkdirExample = () => {
    FS.mkdir(FS.DocumentDirectoryPath + "/" + mkdirParam).then(
      (result) => {
        console.log("file mkdirParam: " + mkdirParam);
        console.log("file Successfully created directory.");
      },
      (err) => {
        console.error("file mkdir: " + err.message);
      }
    );
  };

  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView contentInsetAdjustmentBehavior="automatic" style={styles.scrollView}>
          <Text style={styles.sectionTitle}>{"React Native File Harmony Demo App"}</Text>
          <View style={styles.body}>
            <View style={styles.sectionContainer}>
              <Text style={styles.sectionTitle}>{"mkdir"}</Text>
              <View style={styles.sectionDescription}>
                <TextInput
                  style={styles.input}
                  placeholder="Folder Path"
                  onChangeText={(mkdirParam) => setMkdirParam(mkdirParam)}
                  placeholderTextColor="#9a73ef"
                  autoCapitalize="none"
                />
              </View>
              <Button title="Create Directory" color="#9a73ef" onPress={mkdirExample} />
            </View>
          </View>
        </ScrollView>
      </SafeAreaView>
    </>
  );
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.black,
  },
  engine: {
    position: "absolute",
    right: 0,
  },
  body: {
    backgroundColor: Colors.dark,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: "600",
    color: Colors.white,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: "400",
    color: Colors.dark,
  },
  input: {
    marginTop: 12,
  },
});

export default App;

是否支持autolink RN框架版本
~2.22.0 0.82
~2.21.0 0.77
~2.20.1 0.72
<= 2.20.0-0.1.14@deprecated 0.72

使用AutoLink的工程需要根据该文档配置,Autolink框架指导文档:https://gitcode.com/openharmony-sig/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md

如您使用的版本支持 Autolink,并且工程已接入 Autolink,可跳过ManualLink配置。

ManualLink: 此步骤为手动配置原生依赖项的指导

首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 harmony

2.1. Overrides RN SDK

为了让工程依赖同一个版本的 RN SDK,需要在工程根目录的 oh-package.json5 添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本既可以是一个具体的版本号,也可以是一个模糊版本,还可以是本地存在的 HAR 包或源码目录。

关于该字段的作用请阅读官方说明

{
  "overrides": {
    "@rnoh/react-native-openharmony": "^0.72.38" // ohpm 在线版本
    // "@rnoh/react-native-openharmony" : "./react_native_openharmony.har" // 指向本地 har 包的路径
    // "@rnoh/react-native-openharmony" : "./react_native_openharmony" // 指向源码路径
  }
}

2.2. 引入原生端代码

目前有两种方法:

  • 通过 har 包引入;
  • 直接链接源码。

方法一:通过 har 包引入(推荐)

har 包位于三方库安装路径的 `harmony` 文件夹下。

打开 entry/oh-package.json5,添加以下依赖

"dependencies": {
    "@rnoh/react-native-openharmony": "file:../react_native_openharmony",
    "@react-native-ohos/react-native-fs": "file:../../node_modules/@react-native-ohos/react-native-fs/harmony/fs.har"
  }

点击右上角的 sync 按钮

或者在终端执行:

cd entry
ohpm install

方法二:直接链接源码

如需使用直接链接源码,请参考[直接链接源码说明](./link-source-code.md)

2.3. 配置 CMakeLists 和引入 RNFSPackage

版本 v2.20.1 及以上需要

打开 entry/src/main/cpp/CMakeLists.txt,添加:

project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")

add_subdirectory("${RNOH_CPP_DIR}" ./rn)

# RNOH_BEGIN: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-fs/src/main/cpp" ./fs)
# RNOH_END: manual_package_linking_1

add_library(rnoh_app SHARED
    ${GENERATED_CPP_FILES}
    "./PackageProvider.cpp"
    "${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)

target_link_libraries(rnoh_app PUBLIC rnoh)

# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ target_link_libraries(rnoh_app PUBLIC rnoh_fs)
# RNOH_END: manual_package_linking_2

打开 entry/src/main/cpp/PackageProvider.cpp,添加:

#include "RNOH/PackageProvider.h"
#include "SamplePackage.h"
+ #include "RNFSPackage.h"

using namespace rnoh;

std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
    return {
      std::make_shared<SamplePackage>(ctx),
+     std::make_shared<RNFSPackage>(ctx)
    };
}

2.4. 在 ArkTs 侧引入 FsPackage

打开 entry/src/main/ets/RNPackagesFactory.ts,添加:

import type { RNPackageContext, RNPackage } from 'rnoh/ts';
  ...
+ import { FsPackage } from '@react-native-ohos/react-native-fs/ts';

export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
  return [
    new SamplePackage(ctx),
+   new FsPackage(ctx)
  ];
}

2.5. 运行

点击右上角的 sync 按钮

或者在终端执行:

cd entry
ohpm install

然后编译、运行即可。

3. 约束与限制

3.1. 兼容性

请到三方库相应的 Releases 发布地址查看 Release 配套的版本信息:@react-native-ohos/react-native-fs Releases

本文档内容基于以下版本验证通过:

  1. RNOH:0.72.20; SDK:HarmonyOS NEXT Developer Beta1; IDE:DevEco Studio 5.0.3.200; ROM:3.0.0.18;
  2. RNOH: 0.77.18; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.868; ROM: 6.0.0.112;
  3. RNOH: 0.82.7; SDK: HarmonyOS 6.0.1 Release SDK; IDE: DevEco Studio 6.0.1.260; ROM: 6.0.0.130 SP15.

3.2. 权限要求

需要在 module.json5 中配置以下权限:

"requestPermissions": [
  {
    "name": "ohos.permission.READ_MEDIA",
    "reason": "$string:read_media_permission",
    "usedScene": {
      "abilities": [".MainAbility"],
      "when": "inuse"
    }
  },
  {
    "name": "ohos.permission.WRITE_MEDIA",
    "reason": "$string:write_media_permission",
    "usedScene": {
      "abilities": [".MainAbility"],
      "when": "inuse"
    }
  }
]

3.3. 编译运行API要求

当前三方库所有版本均已实现版本隔离,支持在 `API12+` 工程编译,及 `API12+` ROM运行。

4. 静态方法

"Platform"列表示该属性在原三方库上支持的平台。

"HarmonyOS Support"列为 yes 表示 HarmonyOS 平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。

Name Description Type Required Platform HarmonyOS Support Remark
DocumentDirectoryPath 文档目录 string No iOS/Android yes
CachesDirectoryPath 缓存目录 string No iOS/Android yes
MainBundlePath 主包目录 string No iOS yes
ExternalCachesDirectoryPath 外部缓存目录 string No Android No Android only
DownloadDirectoryPath 下载目录 string No Android/Windows No not available on Harmony
TemporaryDirectoryPath 临时目录 string No iOS/Android yes
LibraryDirectoryPath 库目录 string No iOS yes
ExternalDirectoryPath 外部存储中的应用私有目录 string No Android No Android only
ExternalStorageDirectoryPath 外部存储根目录 string No Android No Android only
PicturesDirectoryPath 图片目录 string No Windows No Windows only
RoamingDirectoryPath 漫游目录 string No Windows No Windows only

DocumentDirectoryPath静态值:

/data/storage/el2/base/haps/entry/files

CachesDirectoryPath静态值:

/data/storage/el2/base/haps/entry/cache

TemporaryDirectoryPath静态值:

/data/storage/el2/base/temp

LibraryDirectoryPath静态值:

/data/storage/el2/base/preferences

5. API

"Platform"列表示该属性在原三方库上支持的平台。

"HarmonyOS Support"列为 yes 表示 HarmonyOS 平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。

Name Description Type Platform Required HarmonyOS Support Remark
mkdir filepath路径创建目录 function Android No yes
exists filepath路径检查是否存在该条目 function iOS/Android No yes
readFile 读取path处的文件并返回内容 function iOS/Android No yes
readFileAssets 读取应用资源文件夹中path处的文件并返回内容 function Android No yes
writeFile 将内容写入filepath路径文件中 function iOS/Android No yes
appendFile 将内容追加到filepath路径文件中 function iOS/Android No yes
copyFile filepath处文件复制到destPath function iOS No yes
unlink 删除filepath处的条目 function iOS/Android No yes
hash 读取path处的文件,并根据指定的algorithm算法返回其校验,算法可以是 md5、sha1、sha256 中的一种 function iOS/Android No partially(md5,sha1,sha256)
moveFile filepath处文件移动到destPath function iOS/Android No yes
read 读取path处文件中从指定position开始的length个字节,并返回内容 function iOS/Android No yes
write contents写入filepath中指定的随机访问位置 function iOS/Android No yes
touch 设置filepath处文件的修改时间戳mtime function iOS/Android No yes
stat 获取filepath处条目的状态信息 function iOS/Android No yes
readDir 读取path路径内容 function iOS/Android No yes
readDirAssets 读取 Android 应用资源文件夹中dirpath路径的内容 function Android No No Android only
readdir 以 Node.js 风格读取目录内容,仅返回名称 function iOS/Android No No No API on Harmony
readFileRes 读取 Android 应用res文件夹中名为filename的文件并返回内容 function Android No No Android only
copyFolder srcFolderPath路径下的内容复制到destFolderPath function Windows No No Windows only
copyFileAssets 将 Android 应用资源文件夹中filepath处的文件复制到指定的destPath 路径 function Android No No Android only
copyFileRes 将 Android 应用res文件夹中名为filename的文件复制到指定的destPath路径 function Android No No Android only
copyAssetsFileIOS 从相机相册读取图片文件并写入destPath function iOS No No iOS only
copyAssetsVideoIOS 将前缀为 'assets-library://asset/asset.MOV?...' 的资源库视频复制到指定目标路径 function iOS No No iOS only
existsAssets 检查 Android 资源文件夹中是否存在该条目 function Android No yes
existsRes 检查 Android 资源文件夹中是否存在名为filename的条目 function Android No No Android only
downloadFile 下载文件 function iOS/Android No yes
stopDownload 中止当前具有此 ID 的下载任务 function iOS/Android No No No API on Harmony
resumeDownload 恢复当前具有此 ID 的下载任务 function iOS No No iOS only
isResumable 检查具有此 ID 的下载任务是否可通过resumeDownload()恢复 function iOS No No iOS only
completeHandlerIOS 在使用后台下载时,通知 iOS 系统已完成对已下载内容的处理 function iOS No No iOS only
uploadFiles 上传文件,百分比可以通过totalBytesSent除以totalBytesExpectedToSend计算得出 function iOS/Android No yes
stopUpload 中止当前具有此 ID 的上传任务 function iOS No No iOS only
getFSInfo 返回文件系统的存储空间信息 function iOS/Android No No No API on Harmony
scanFile 使用 Media Scanner扫描文件 function Android No No Android only
getAllExternalFilesDirs 返回一个数组,包含应用程序可以存放其拥有的持久性文件的所有共享/外部存储设备上,应用专属目录的绝对路径 function Android No No Android only
pathForGroup 返回所有具有相同安全组标识符的应用程序所共享的目录的绝对路径 function iOS No No iOS only

mkdir方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 文件夹创建路径 string yes iOS/Android yes
options 创建文件夹时配置选项 MkdirOptions no IOS no

exists方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 文件所在路径 string yes iOS/Android yes

readFile方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 文件所在路径 string yes iOS/Android yes
encodingOrOptions 编码选项 any no iOS/Android yes

readFileAssets方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 文件所在路径 string yes iOS/Android yes
encodingOrOptions 编码选项 any no iOS/Android yes

Writefile方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 文件所在路径 string yes iOS/Android yes
contents 要写入的内容 string yes iOS/Android yes
encodingOrOptions 编码选项 any no iOS/Android yes

appendFile方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 文件所在路径 string yes iOS/Android yes
contents 要追加的内容 string yes iOS/Android yes
encodingOrOptions 编码选项 stirng no iOS/Android yes

copyFile方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 源文件所在路径 string yes iOS/Android yes
destPath 目标路径 string yes iOS/Android yes
options IOS文件保护级别选项 FileOptions no iOS no

unlink方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 源文件所在路径 string yes iOS/Android yes

hash方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 源文件所在路径 string yes iOS/Android yes
algorithm 校验算法 string yes iOS/Android yes

moveFile方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 源文件所在路径 string yes iOS/Android yes
destPath 目标路径 string yes iOS/Android yes
options IOS文件保护级别选项 FileOptions no iOS no

read方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 文件所在路径 string yes iOS/Android yes
length 读取的字节数 number no iOS/Android yes
positon 读取的起始位置 number no iOS/Android yes
encodingOrOptions 编码选项 any no iOS/Android yes

write方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 文件所在路径。 string yes iOS/Android yes
contents 写入的内容 string yes iOS/Android yes
positon 写入的起始位置 number no iOS/Android yes
encodingOrOptions 编码选项 any no iOS/Android yes

touch方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 文件所在路径 string yes iOS/Android yes
mtime 修改时间 Date no iOS/Android yes
ctime 状态变更时间 Date no iOS/Android yes

stat方法参数

Name Description Type Required Platform HarmonyOS Support
filepath 文件所在路径 string yes iOS/Android yes

readDir 方法参数

Name Description Type Required Platform HarmonyOS Support
dirpath 文件夹所在路径 string yes iOS/Android yes

6. 遗留问题

7. 其他

8. 开源协议

本项目基于 The MIT License (MIT) ,请自由地享受和参与开源。