Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

@ohmi/react-native-fs

Package Overview
Dependencies
Maintainers
7
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ohmi/react-native-fs

Native filesystem access for react-native

latest
Source
npmnpm
Version
2.20.1-rc.2
Version published
Maintainers
7
Created
Source

模板版本:v0.2.2

@ohmi/react-native-fs

1. 安装与使用

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

npm

npm install @ohmi/react-native-fs

yarn

yarn add @ohmi/react-native-fs

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

[!WARNING] 使用时 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;

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

首先需要使用 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 包引入(推荐)

[!TIP] har 包位于三方库安装路径的 harmony 文件夹下。

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

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

点击右上角的 sync 按钮

或者在终端执行:

cd entry
ohpm install

方法二:直接链接源码

[!TIP] 如需使用直接链接源码,请参考直接链接源码说明

2.3. 配置 CMakeLists 和引入 RNFSPackage

[!TIP] 版本 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}/@ohmi/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 '@ohmi/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 配套的版本信息:@ohmi/react-native-fs Releases

4. 静态方法

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

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

NameDescriptionTypeRequiredPlatformHarmonyOS SupportRemark
DocumentDirectoryPathSystem PathstringNoiOS/Androidyes
CachesDirectoryPathSystem PathstringNoiOS/Androidyes
MainBundlePathSystem PathstringNoiOSyes
ExternalCachesDirectoryPathSystem PathstringNoAndroidNoAndroid only
DownloadDirectoryPathSystem PathstringNoAndroid/WindowsNonot available on Harmony
TemporaryDirectoryPathSystem PathstringNoiOS/Androidyes
LibraryDirectoryPathSystem PathstringNoiOSyes
ExternalDirectoryPathSystem PathstringNoAndroidNoAndroid only
ExternalStorageDirectoryPathSystem PathstringNoAndroidNoAndroid only
PicturesDirectoryPathSystem PathstringNoWindowsNoWindows only
RoamingDirectoryPathSystem PathstringNoWindowsNoWindows only

5. API

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

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

NameDescriptionTypePlatformRequiredHarmonyOS SupportRemark
mkdirCreate a directory at filepath.functionAndroidNoyes
existsCheck if the item exists at filepath.functioniOS/AndroidNoyes
readFileReads the file at path and return contents.functioniOS/AndroidNoyes
readFileAssetsReads the file at path in the harmony app's assets folder and return contents.functionAndroidNoyes
writeFileWrite the contents to filepath.functioniOS/AndroidNoyes
appendFileAppend the contents to filepath.functioniOS/AndroidNoyes
copyFileCopies the file located at filepath to destPath.functioniOSNoyes
unlinkUnlinks the item at filepath.functioniOS/AndroidNoyes
hashReads the file at path and returns its checksum as determined by algorithm, which can be one of md5, sha1, sha256.functioniOS/AndroidNopartially
moveFileMoves the file located at filepath to destPath.functioniOS/AndroidNoyes
readReads length bytes from the given position of the file at path and returns contents.functioniOS/AndroidNoyes
writeWrite the contents to filepath at the given random access position.functioniOS/AndroidNoyes
touchSets the modification timestamp mtimeof the file at filepath.functioniOS/AndroidNoyes
statStats an item at filepath.functioniOS/AndroidNoyes
readDirReads the contents of path.functioniOS/AndroidNoyes
readDirAssetsReads the contents of dirpath in the Android app's assets folder.functionAndroidNoNoAndroid only
readdirNode.js style version of readDir that returns only the names.functioniOS/AndroidNoNoNo API on Harmony
readFileResReads the file named filename in the Android app's res folder and return contents.functionAndroidNoNoAndroid only
copyFolderCopies the contents located at srcFolderPath to destFolderPath.functionWindowsNoNoWindows only
copyFileAssetsCopies the file at filepath in the Android app's assets folder and copies it to the given destPath path.functionAndroidNoNoAndroid only
copyFileResCopies the file named filename in the Android app's res folder and copies it to the given destPath path.functionAndroidNoNoAndroid only
copyAssetsFileIOSReads an image file from Camera Roll and writes to destPath.functioniOSNoNoiOS only
copyAssetsVideoIOSCopies a video from assets-library, that is prefixed with 'assets-library://asset/asset.MOV?...' to a specific destination.functioniOSNoNoiOS only
existsAssetsCheck in the Android assets folder if the item exists.functionAndroidNoyes
existsResCheck in the Android res folder if the item named filename exists.functionAndroidNoNoAndroid only
downloadFileAbort the current download job with this ID.functioniOS/AndroidNoyes
stopDownloadAbort the current download job with this ID.functioniOS/AndroidNoNoNo API on Harmony
resumeDownloadResume the current download job with this ID.functioniOSNoNoiOS only
isResumableCheck if the the download job with this ID is resumable with resumeDownload().functioniOSNoNoiOS only
completeHandlerIOSFor use when using background downloads, tell iOS you are done handling a completed download.functioniOSNoNoiOS only
uploadFilesPercentage can be computed easily by dividing totalBytesSent by totalBytesExpectedToSend.functioniOS/AndroidNoNoNo API on Harmony
stopUploadAbort the current upload job with this ID.functioniOSNoNoiOS only
getFSInfoReturns an object with the following properties.functioniOS/AndroidNoNoNo API on Harmony
scanFileScan the file using Media Scanner.functionAndroidNoNoAndroid only
getAllExternalFilesDirsReturns an array with the absolute paths to application-specific directories on all shared/external storage devices where the application can place persistent files it owns.functionAndroidNoNoAndroid only
pathForGroupReturns the absolute path to the directory shared for all applications with the same security group identifier.functioniOSNoNoiOS only

6. 遗留问题

  • HarmonyOS 的 hash 哈希 API 中关于算法参数 algorithm 目前仅支持"md5"、"sha1"、 "sha256",其他相关算法参数目前不支持,问题: issue#1
  • 原库部分接口在 HarmonyOS 中没有对应文件路径常量及接口处理相关逻辑,问题: issue#2

7. 其他

8. 开源协议

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

Keywords

react-component

FAQs

Package last updated on 28 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts