npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ionic-native-ohos/file

v5.36.0

Published

Ionic Native - Native plugins for ionic apps

Readme

@ionic-native/file

zh-CN en

本项目基于 @ionic-native/[email protected]开发。

简介

一个为应用提供文件读写功能的插件,支持对设备上的文件进行读写访问。兼容Android、iOS和OpenHarmony平台,为跨平台应用开发提供统一的文件管理能力。本文档主要说明在OpenHarmony系统中的应用。

在移动应用开发中,文件操作是常见的需求。@ionic-native/file插件通过封装原生平台API,为开发者提供了统一的跨平台接口,无需深入原生开发即可实现文件的创建、读取、写入、删除等功能。

支持平台

  • OpenHarmony:5.0+

下载安装

通过命令行或手动引入即可快速安装插件,支持从npm仓库获取。

命令行安装(推荐)

安装hionic CLI:

npm install -g hionic

以下两种方式中任选其一即可,无需重复操作:

npm安装:

# 安装插件
npm install @ionic-native/file

# 同步插件
hionic sync

hionic CLI安装:

hionic plugin add @ionic-native/file

手动引入安装

1.添加插件配置

根据plugin.xmlconfig-json项,找到entry模块中config.xml文件,并根据param标签添加配置

<feature name="File">
  <param name="harmony-package" value="FileUtils" />
</feature>

2.修改 CMake 配置

根据plugin.xmlCMakeLists项,找到cordova模块,路径为target字段的文件CMakeLists.txt,添加add_library

add_library(cordova SHARED
  // ...
  File/FileUtils.cpp
  // ...
)

3.复制源码文件

根据plugin.xmlsource-file项,将src字段的路径代码复制到cordova模块中target-dir字段的目录中:

将源码中src/main/cpp/file目录下的FileUtils.h、FileUtils.cpp等文件引入到cordova模块中src/main/cpp/File目录下。

将源码中src/main/ets/components/File目录下的File.ets文件引入到cordova模块中src/main/ets/components/File目录下。

4.添加 ArkTS 配置

cordova模块的build-profile.json5文件中,buildOption/arkOptions/runtimeOnly/sources配置项数组中加入步骤3中拷贝的ets文件路径:

"buildOption":{
  "arkOptions": {
    "runtimeOnly": {
      "sources": [
        // ...
        "./src/main/ets/components/File/File.ets"
        // ...
      ]
    }
  }
}

编译注意事项

由于插件依赖C++ 17环境,编译前需要在CMakeLists.txt中添加C++标准支持:

set(CMAKE_CXX_STANDARD 17)

卸载

# hionic CLI卸载
hionic plugin remove @ionic-native/file

约束与限制

兼容性

在以下版本中已测试通过:

  1. SDK: 5.0.5(17); IDE: DevEco Studio: 6.0.0; ROM: 5.1.0.150;

权限要求

不涉及

使用示例

示例1:将一段文本写入文件

实现将一段文本写入指定文件的功能。

import { File } from '@ionic-native/file';

const params = ref({
  path: File.dataDirectory,
  fileName: 'demo.txt',
  text: 'Hello from plugin demo',
  dirName: 'demo-dir',
  encoding: 'UTF-8',
  replace: true
});

const handleWriteFile = async () => {
  try {
    const result = await File.writeFile(params.value.path, params.value.fileName, params.value.text, { replace: params.value.replace });
    console.log('已写入:', result?.name);
  } catch (error) {
    console.error('writeFile failed:', error);
  }
};

示例2:从文件读取内容

实现从指定文件读取文本内容的功能。

const handleReadAsText = async () => {
  try {
    const content = await File.readAsText(params.value.path, params.value.fileName);
    console.log('文件内容:', content);
  } catch (error) {
    console.error('readAsText failed:', error);
  }
};

示例3:读取文件并以base64编码的数据URL形式返回数据

实现读取文件并返回base64编码数据URL的功能。

const handleReadAsDataURL = async () => {
  try {
    const dataUrl = await File.readAsDataURL(params.value.path, params.value.fileName);
    console.log('Data URL:', dataUrl.substring(0, 100) + '...');
  } catch (error) {
    console.error('readAsDataURL failed:', error);
  }
};

示例4:检查某个路径或目录中是否存在文件

实现检查指定路径下文件是否存在的功能。

const handleCheckFile = async () => {
  try {
    const exists = await File.checkFile(params.value.path, params.value.fileName);
    console.log(exists ? '文件存在' : '文件不存在');
  } catch (error) {
    console.error('checkFile failed:', error);
  }
};

示例5:从指定位置移除文件

实现从指定位置移除文件的功能。

const handleRemoveFile = async () => {
  try {
    await File.removeFile(params.value.path, params.value.fileName);
    console.log('文件已删除');
  } catch (error) {
    console.error('removeFile failed:', error);
  }
};

示例6:在指定路径下创建一个新目录

实现在指定路径下创建新目录的功能。

const handleCreateDir = async () => {
  try {
    const result = await File.createDir(params.value.path, params.value.dirName, params.value.replace);
    console.log('目录已创建:', result?.name);
  } catch (error) {
    console.error('createDir failed:', error);
  }
};

示例7:检查某个路径中是否存在目录

实现检查指定路径下目录是否存在的功能。

const handleCheckDir = async () => {
  try {
    const exists = await File.checkDir(params.value.path, params.value.dirName);
    console.log(exists ? '目录存在' : '目录不存在');
  } catch (error) {
    console.error('checkDir failed:', error);
  }
};

示例8:删除给定路径下的目录

实现删除给定路径下目录的功能。

const handleRemoveDir = async () => {
  try {
    await File.removeDir(params.value.path, params.value.dirName);
    console.log('目录已删除');
  } catch (error) {
    console.error('removeDir failed:', error);
  }
};

示例9:列出给定路径中的文件和目录

实现列出给定路径中文件和目录的功能。

const handleListDir = async () => {
  try {
    const entries = await File.listDir(params.value.path, params.value.dirName);
    const names = entries.map((e: any) => e.name).join(', ');
    console.log('目录内容:', names || '(空目录)');
  } catch (error) {
    console.error('listDir failed:', error);
  }
};

示例10:获取磁盘剩余空间

实现获取设备磁盘剩余空间的功能。

const handleGetFreeDiskSpace = async () => {
  try {
    const bytes = await File.getFreeDiskSpace();
    const mb = (bytes / (1024 * 1024)).toFixed(2);
    console.log('剩余空间:', mb, 'MB');
  } catch (error) {
    console.error('getFreeDiskSpace failed:', error);
  }
};

示例11:在指定路径创建新文件

实现在指定路径创建新文件的功能。

const handleCreateFile = async () => {
  try {
    const result = await File.createFile(params.value.path, params.value.fileName, params.value.replace);
    console.log('文件已创建:', result?.name);
  } catch (error) {
    console.error('createFile failed:', error);
  }
};

示例12:写入现有文件

实现写入现有文件的功能。

const handleWriteExistingFile = async () => {
  try {
    await File.writeExistingFile(params.value.path, params.value.fileName, params.value.text);
    console.log('已写入现有文件');
  } catch (error) {
    console.error('writeExistingFile failed:', error);
  }
};

示例13:读取文件并以二进制数据形式返回数据

实现读取文件并以二进制字符串形式返回数据的功能。

const handleReadAsBinaryString = async () => {
  try {
    const content = await File.readAsBinaryString(params.value.path, params.value.fileName);
    console.log('二进制内容:', content.substring(0, 100) + '...');
  } catch (error) {
    console.error('readAsBinaryString failed:', error);
  }
};

示例14:读取文件并将数据作为ArrayBuffer返回

实现读取文件并以ArrayBuffer形式返回数据的功能。

const handleReadAsArrayBuffer = async () => {
  try {
    const buffer = await File.readAsArrayBuffer(params.value.path, params.value.fileName);
    console.log('ArrayBuffer:', buffer.byteLength, 'bytes');
  } catch (error) {
    console.error('readAsArrayBuffer failed:', error);
  }
};

示例15:将文件移动到指定路径

实现将文件移动到指定路径的功能。

const handleMoveFile = async () => {
  try {
    const newFileName = params.value.fileName + '.moved';
    const result = await File.moveFile(params.value.path, params.value.fileName, params.value.path, newFileName);
    console.log('文件已移动至:', result?.name);
  } catch (error) {
    console.error('moveFile failed:', error);
  }
};

示例16:用多种方法复制文件

实现复制文件的功能。如果文件已存在,则复制失败。

const handleCopyFile = async () => {
  try {
    const newFileName = params.value.fileName + '.copy';
    const result = await File.copyFile(params.value.path, params.value.fileName, params.value.path, newFileName);
    console.log('文件已复制至:', result?.name);
  } catch (error) {
    console.error('copyFile failed:', error);
  }
};

示例17:将目录移动到指定路径

实现将目录移动到指定路径的功能。

const handleMoveDir = async () => {
  try {
    const newDirName = params.value.dirName + '-moved';
    const result = await File.moveDir(params.value.path, params.value.dirName, params.value.path, newDirName);
    console.log('目录已移动至:', result?.name);
  } catch (error) {
    console.error('moveDir failed:', error);
  }
};

示例18:使用多种方法复制目录

实现复制目录的功能。如果目标目录已存在,则复制将失败。

const handleCopyDir = async () => {
  try {
    const newDirName = params.value.dirName + '-copy';
    const result = await File.copyDir(params.value.path, params.value.dirName, params.value.path, newDirName);
    console.log('目录已复制至:', result?.name);
  } catch (error) {
    console.error('copyDir failed:', error);
  }
};

示例19:从指定位置删除所有文件和目录

实现递归删除目录及其所有内容的功能。

const handleRemoveRecursively = async () => {
  try {
    await File.removeRecursively(params.value.path, params.value.dirName);
    console.log('目录已递归删除');
  } catch (error) {
    console.error('removeRecursively failed:', error);
  }
};

示例20:解析本地文件系统URL

实现解析本地文件系统URL的功能。

const handleResolveLocalFilesystemUrl = async () => {
  try {
    const base = params.value.path ?? '';
    const sep = base.endsWith('/') ? '' : '/';
    const fileUrl = base + sep + params.value.fileName;
    const result = await File.resolveLocalFilesystemUrl(fileUrl);
    console.log('已解析:', result.name);
  } catch (error) {
    console.error('resolveLocalFilesystemUrl failed:', error);
  }
};

示例21:解析本地目录URL

实现解析本地目录URL的功能。

const handleResolveDirectoryUrl = async () => {
  try {
    const dirUrl = params.value.path + params.value.dirName + '/';
    const result = await File.resolveDirectoryUrl(dirUrl);
    console.log('已解析目录:', result?.name);
  } catch (error) {
    console.error('resolveDirectoryUrl failed:', error);
  }
};

示例22:显示所有可用作存储的路径

实现显示所有可用目录路径的功能。

const fileDirectories = {
  applicationDirectory: File.applicationDirectory,
  applicationStorageDirectory: File.applicationStorageDirectory,
  dataDirectory: File.dataDirectory,
  cacheDirectory: File.cacheDirectory,
  externalApplicationStorageDirectory: File.externalApplicationStorageDirectory,
  externalDataDirectory: File.externalDataDirectory,
  externalCacheDirectory: File.externalCacheDirectory,
  externalRootDirectory: File.externalRootDirectory,
  tempDirectory: File.tempDirectory,
  syncedDataDirectory: File.syncedDataDirectory,
  documentsDirectory: File.documentsDirectory,
  sharedDirectory: File.sharedDirectory
};

const handleShowDirectories = () => {
  console.log('File 共有 12 个目录属性:', fileDirectories);
};

使用说明

插件在全局对象 File 下暴露所有功能接口,使用前需确保设备就绪事件(deviceready)已触发。

1. 检查目录是否存在

检查某个路径中是否存在目录。

方法签名

File.checkDir(path, dir)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 目录路径 | | dir | string | 目录名称 |

返回值

Promise<boolean> - 目录是否存在

2. 创建目录

在指定路径中创建新目录。

方法签名

File.createDir(path, dirName, replace)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 父目录路径 | | dirName | string | 新目录名称 | | replace | boolean | 是否替换已存在的目录 |

返回值

Promise<DirectoryEntry> - 创建的目录条目

3. 删除目录

删除给定路径下的目录。

方法签名

File.removeDir(path, dirName)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 目录路径 | | dirName | string | 目录名称 |

返回值

Promise<RemoveResult> - 删除结果

4. 移动目录

将目录移动到指定路径。

方法签名

File.moveDir(path, dirName, newPath, newDirName)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 源目录路径 | | dirName | string | 源目录名称 | | newPath | string | 目标路径 | | newDirName | string | 新目录名称 |

返回值

Promise<DirectoryEntry> - 移动后的目录条目

5. 复制目录

使用多种方法复制目录。如果目标目录已存在,则复制将失败。

方法签名

File.copyDir(path, dirName, newPath, newDirName)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 源目录路径 | | dirName | string | 源目录名称 | | newPath | string | 目标路径 | | newDirName | string | 新目录名称 |

返回值

Promise<DirectoryEntry> - 复制后的目录条目

6. 列出目录内容

列出给定路径中的文件和目录。

方法签名

File.listDir(path, dirName)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 目录路径 | | dirName | string | 目录名称 |

返回值

Promise<Entry[]> - 条目数组

7. 递归删除目录

从指定位置删除所有文件和目录。

方法签名

File.removeRecursively(path, dirName)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 目录路径 | | dirName | string | 目录名称 |

返回值

Promise<RemoveResult> - 删除结果

8. 检查文件是否存在

检查某个路径或目录中是否存在文件。

方法签名

File.checkFile(path, file)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 文件路径 | | file | string | 文件名称 |

返回值

Promise<boolean> - 文件是否存在

9. 创建文件

在指定路径创建一个新文件。

方法签名

File.createFile(path, file, replace)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 文件路径 | | file | string | 文件名称 | | replace | boolean | 是否替换已存在的文件 |

返回值

Promise<FileEntry> - 创建的文件条目

10. 删除文件

从指定位置移除文件。

方法签名

File.removeFile(path, fileName)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 文件路径 | | fileName | string | 文件名称 |

返回值

Promise<RemoveResult> - 删除结果

11. 写入文件

将新文件写入所需位置。

方法签名

File.writeFile(path, fileName, text, options)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 文件路径 | | fileName | string | 文件名称 | | text | string | 写入内容 | | options | object | 可选参数,如replace |

返回值

Promise<any> - 写入结果

12. 写入现有文件

写入现有文件。

方法签名

File.writeExistingFile(path, fileName, text)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 文件路径 | | fileName | string | 文件名称 | | text | string | 写入内容 |

返回值

Promise<void> - 完成状态

13. 读取文件为文本

将文件内容作为文本读取。

方法签名

File.readAsText(path, file)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 文件路径 | | file | string | 文件名称 |

返回值

Promise<string> - 文件内容

14. 读取文件为Data URL

读取文件并返回经过base64编码的数据URL。

方法签名

File.readAsDataURL(path, file)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 文件路径 | | file | string | 文件名称 |

返回值

Promise<string> - Base64编码的数据URL

15. 读取文件为二进制字符串

读取文件并以二进制数据形式返回数据。

方法签名

File.readAsBinaryString(path, file)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 文件路径 | | file | string | 文件名称 |

返回值

Promise<string> - 二进制字符串

16. 读取文件为ArrayBuffer

读取文件并以ArrayBuffer形式返回数据。

方法签名

File.readAsArrayBuffer(path, file)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 文件路径 | | file | string | 文件名称 |

返回值

Promise<ArrayBuffer> - ArrayBuffer数据

17. 移动文件

将文件移动到指定路径。

方法签名

File.moveFile(path, fileName, newPath, newFileName)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 源文件路径 | | fileName | string | 源文件名称 | | newPath | string | 目标路径 | | newFileName | string | 新文件名称 |

返回值

Promise<Entry> - 移动后的文件条目

18. 复制文件

用多种方法复制文件。如果文件已存在,则复制失败。

方法签名

File.copyFile(path, fileName, newPath, newFileName)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | path | string | 源文件路径 | | fileName | string | 源文件名称 | | newPath | string | 目标路径 | | newFileName | string | 新文件名称 |

返回值

Promise<Entry> - 复制后的文件条目

19. 解析本地文件系统URL

解析本地文件系统URL。

方法签名

File.resolveLocalFilesystemUrl(fileUrl)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | fileUrl | string | 文件URL |

返回值

Promise<Entry> - 文件条目

20. 解析本地目录URL

解析本地目录URL。

方法签名

File.resolveDirectoryUrl(directoryUrl)

| 参数 | 类型 | 描述 | | ---- | ---- | ---- | | directoryUrl | string | 目录URL |

返回值

Promise<DirectoryEntry> - 目录条目

21. 获取磁盘剩余空间

获取设备磁盘剩余空间。

方法签名

File.getFreeDiskSpace()

返回值

Promise<number> - 剩余空间字节数

目录结构

|---- 目录
|     |---- src/main  # 插件的实现代码
|           |---- cpp  # C++ 代码
|           |---- ets  # ArkTS 代码
|     |---- www    # Web 侧代码
|     |---- README.md          # 说明文档
|     |---- package.json       # 配置文件
|     |---- plugin.xml         # 插件配置文件

贡献代码

使用过程中发现任何问题都可以提 Issue,当然,也非常欢迎发 PR 共建。

许可证

本插件基于 MIT License 开源,详见 LICENSE 文件。