{"_id":"@capacitor-ohos/preferences","_rev":"2-d5d2a07a2fcf1f33a7e58b9a3ab1c6b1","name":"@capacitor-ohos/preferences","dist-tags":{"latest":"8.0.1"},"versions":{"8.0.0":{"name":"@capacitor-ohos/preferences","version":"8.0.0","keywords":["capacitor","plugin","native"],"author":{"url":"Group","name":"Huawei Device Co., Ltd and iSoftStone Information Technology"},"license":"MIT","_id":"@capacitor-ohos/preferences@8.0.0","maintainers":[{"name":"luqi_tan","email":"295099422@qq.com"}],"bugs":{"url":"https://gitcode.com/CPF-Ionic/capacitor-preferences/issues"},"dist":{"shasum":"44c8543a9a98340bb486e5753a16f03be158f1d7","tarball":"https://registry.npmjs.org/@capacitor-ohos/preferences/-/preferences-8.0.0.tgz","fileCount":10,"integrity":"sha512-E9HbGuEmBE04tNSm5gvPpvdD1E9lAT3+iKrDsRdkBddpJt6KH0jTfoJayAGcqhoVU2r0RbJRdjTxaokvWExNiA==","signatures":[{"sig":"MEUCIQD5Und5Sp2sIJUAnQVCf5JglwUmUA9jMPS6jlbh3FoczgIgX4PNY6dzLgAZGhFMNV+KjTd5mKCGkqouMKvs9hYtZR4=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":76462},"gitHead":"698ca68bf14b939d2be35a626d8cde085444f5b1","_npmUser":{"name":"luqi_tan","email":"295099422@qq.com"},"capacitor":{"id":"@capacitor/preferences","platforms":["openharmony"]},"repository":{"url":"gitcode:CPF-Ionic/capacitor-preferences","type":"git"},"_npmVersion":"10.5.1","description":"The Preferences API provides a simple key/value persistent store for lightweight data.","directories":{},"_nodeVersion":"22.0.0","_hasShrinkwrap":false,"_npmOperationalInternal":{"tmp":"tmp/preferences_8.0.0_1777546022330_0.0001286709480905479","host":"s3://npm-registry-packages-npm-production"}},"8.0.1":{"name":"@capacitor-ohos/preferences","version":"8.0.1","description":"The Preferences API provides a simple key/value persistent store for lightweight data.","capacitor":{"id":"@capacitor/preferences","platforms":["openharmony"]},"repository":{"type":"git","url":"gitcode:CPF-Ionic/capacitor-preferences"},"bugs":{"url":"https://gitcode.com/CPF-Ionic/capacitor-preferences/issues"},"keywords":["capacitor","plugin","native"],"author":{"name":"Huawei Device Co., Ltd and iSoftStone Information Technology","url":"Group"},"license":"MIT","_id":"@capacitor-ohos/preferences@8.0.1","gitHead":"9e76174407578b87c4f83feace5b239c1583713f","_nodeVersion":"22.0.0","_npmVersion":"10.5.1","dist":{"integrity":"sha512-zstP+gqAddjG1rrsYAVk3yqKZl2qme8kk6DKqEYMwwCP8qHH/xpB5aVzRLBn8wt8jw4RCHA3szrnFcAHYUKCkw==","shasum":"d505747307050b70360061081a8e2b3b4c141fbb","tarball":"https://registry.npmjs.org/@capacitor-ohos/preferences/-/preferences-8.0.1.tgz","fileCount":10,"unpackedSize":76675,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQCRk3bfIZ7cV+7QUhQqLGdulGH4P0b+Z8dN3KWdhscIcwIhAKS+r0pATXHKt9y1ScFPgAEOF1RQUZ1dkz3FD66jzmN2"}]},"_npmUser":{"name":"luqi_tan","email":"295099422@qq.com"},"directories":{},"maintainers":[{"name":"luqi_tan","email":"295099422@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/preferences_8.0.1_1784796000767_0.543597397540794"},"_hasShrinkwrap":false}},"time":{"created":"2026-04-30T10:47:02.232Z","modified":"2026-07-23T08:40:01.031Z","8.0.0":"2026-04-30T10:47:02.467Z","8.0.1":"2026-07-23T08:40:00.893Z"},"bugs":{"url":"https://gitcode.com/CPF-Ionic/capacitor-preferences/issues"},"author":{"name":"Huawei Device Co., Ltd and iSoftStone Information Technology","url":"Group"},"license":"MIT","keywords":["capacitor","plugin","native"],"repository":{"type":"git","url":"gitcode:CPF-Ionic/capacitor-preferences"},"description":"The Preferences API provides a simple key/value persistent store for lightweight data.","maintainers":[{"name":"luqi_tan","email":"295099422@qq.com"}],"readme":"# <center>`@capacitor/preferences`</center>\r\n[![zh-CN](https://img.shields.io/badge/lang-中文-blue.svg)](README.md)\r\n[![en](https://img.shields.io/badge/lang-English-blue.svg)](README.en.md)\r\n\r\n本项目基于 [@capacitor/preferences@8.0.0](https://www.npmjs.com/package/@capacitor/preferences) 开发。\r\n\r\n## 简介\r\n\r\n提供了一个简单的键/值持久化存储，适用于轻量级数据。本插件是 capacitor 生态系统中的核心插件，为跨平台应用开发提供设备差异化适配能力，兼容 capacitor 的 Android、iOS 等主流移动平台及浏览器环境中使用，使用值 NativeStorage 可实现与 cordova-plugin-nativestorage 插件的向后兼容。本文档仅说明在 OpenHarmony 系统中的使用情况。\r\n\r\n## 支持平台\r\n\r\n- **OpenHarmony**：5.0+\r\n\r\n## 下载安装\r\n\r\n通过命令行或手动引入即可快速安装插件，支持从npm仓库获取。\r\n\r\n### 命令行安装（推荐）\r\n\r\n安装hionic CLI：\r\n\r\n```bash\r\nnpm install -g hionic\r\n```\r\n\r\n以下两种方式中**任选其一**即可，无需重复操作：\r\n\r\nnpm安装：\r\n\r\n```bash\r\n# 安装插件\r\nnpm install @capacitor/preferences\r\n\r\n# 同步插件\r\nhionic sync openharmony\r\n```\r\n\r\nhionic CLI安装：\r\n\r\n```bash\r\nhionic plugin add @capacitor/preferences\r\n```\r\n\r\n### 手动引入安装\r\n\r\n根据插件源码中 `plugin.xml` 配置在项目中引入插件：\r\n\r\n#### 1. 添加插件配置\r\n\r\n根据 `plugin.xml` 的 `config-json` 项，找到 `entry` 模块中 `capacitor.plugins.json` 文件，并根据 `param` 标签添加配置如下：\r\n\r\n```json\r\n{\r\n  \"pkg\": \"@capacitor/preferences\",\r\n  \"classpath\": \"Preferences\"\r\n}\r\n```\r\n\r\n#### 2. 修改 CMake 配置\r\n\r\n根据 `plugin.xml` 的 `CMakeLists` 项，找到 `capacitor` 模块，路径为 `target` 字段的 `CMakeLists.txt` 文件，并添加 `add_subdirectory` 和 `target_link_libraries` 如下：\r\n\r\n```cmake\r\n// ...\r\nadd_subdirectory(Preferences)\r\n// ...\r\n\r\n// ...\r\ntarget_link_libraries(capacitor PUBLIC\r\n  \"-Wl,--whole-archive\"\r\n  // ...\r\n  Preferences\r\n  // ...\r\n  \"-Wl,--no-whole-archive\"\r\n);\r\n```\r\n\r\n#### 3. 复制源码文件\r\n\r\n根据 `plugin.xml` 的 `source-file` 项，根据 `src` 字段找到需要复制的文件，并复制到对应的目录：\r\n\r\n将源码中 src/main/cpp/Preferences 目录下的 Preferences.h、Preferences.cpp、CMakeLists.txt 文件引入到 capacitor 模块中 src/main/cpp/Preferences 目录下。\r\n\r\n将源码中 src/main/ets/components/Preferences 目录下的 Preferences.ets 文件引入到 capacitor 模块中 src/main/ets/components/Preferences 目录下。\r\n\r\n在 `capacitor` 模块的 `build-profile.json5` 文件中，`buildOption/arkOptions/runtimeOnly/sources` 配置项数组中加入拷贝的 ets 文件路径：\r\n\r\n```json\r\n\"buildOption\": {\r\n  // ...\r\n  \"arkOptions\": {\r\n    \"runtimeOnly\": [\r\n      // ...\r\n      \"./src/main/ets/components/Preferences/Preferences.ets\"\r\n      // ...\r\n    ]\r\n  }\r\n}\r\n```\r\n\r\n## 卸载\r\n\r\n```bash\r\n# 卸载 preferences 插件\r\nhionic plugin remove @capacitor/preferences\r\n```\r\n\r\n## 约束与限制\r\n\r\n### 兼容性\r\n\r\n在以下版本中已测试通过：\r\n\r\n1. SDK: 5.0.5(17); IDE: DevEco Studio: 6.0.0; ROM: 5.1.0.150;\r\n\r\n### 权限要求\r\n\r\n不需要额外权限。\r\n\r\n## 使用示例\r\n\r\n### 示例 1：基础用法 - 设置和获取键值对\r\n\r\n```typescript\r\nimport { Preferences } from '@capacitor/preferences';\r\n\r\n// 设置键值对\r\nconst setValue = async () => {\r\n  try {\r\n    await Preferences.set({\r\n      key: 'user_name',\r\n      value: '张三'\r\n    });\r\n    console.log('数据已成功保存');\r\n  } catch (error) {\r\n    console.error('保存失败：', error);\r\n  }\r\n};\r\n\r\n// 获取键值对\r\nconst getValue = async () => {\r\n  try {\r\n    const ret = await Preferences.get({ key: 'user_name' });\r\n    console.log('获取到的数据:', ret.value);\r\n  } catch (error) {\r\n    console.error('获取失败：', error);\r\n  }\r\n};\r\n```\r\n\r\n### 示例 2：获取所有键名\r\n\r\n```typescript\r\nimport { Preferences } from '@capacitor/preferences';\r\n\r\nconst getAllKeys = async () => {\r\n  try {\r\n    const ret = await Preferences.keys();\r\n    console.log('所有键名:', ret.keys);\r\n  } catch (error) {\r\n    console.error('获取键名失败：', error);\r\n  }\r\n};\r\n```\r\n\r\n### 示例 3：清除特定键或全部数据\r\n\r\n```typescript\r\nimport { Preferences } from '@capacitor/preferences';\r\n\r\n// 删除特定键\r\nconst removeKey = async () => {\r\n  try {\r\n    await Preferences.remove({ key: 'user_name' });\r\n    console.log('键已成功删除');\r\n  } catch (error) {\r\n    console.error('删除失败：', error);\r\n  }\r\n};\r\n\r\n// 清空所有数据\r\nconst clearAllData = async () => {\r\n  try {\r\n    await Preferences.clear();\r\n    console.log('所有数据已清空');\r\n  } catch (error) {\r\n    console.error('清空失败：', error);\r\n  }\r\n};\r\n```\r\n\r\n## 使用说明\r\n\r\n### 接口方法\r\n\r\n| 方法名         | 调用方式                                                     | 入参类型                                  | 功能描述                                                     |\r\n| -------------- | ------------------------------------------------------------ | ----------------------------------------- | ------------------------------------------------------------ |\r\n| configure(...) | Preferences.configure([ConfigureOptions](#configureoptions)) | **[ConfigureOptions](#configureoptions)** | 配置 Preferences 存储选项，指定存储组名，使用值 NativeStorage 可提供与 cordova-plugin-nativestorage 的向后兼容性 |\r\n| get(...)       | Preferences.get([GetOptions](#getoptions]))                  | **[GetOptions](#getoptions)**             | 根据键获取存储的值                                           |\r\n| set(...)       | Preferences.set([SetOptions](#setoptions]))                  | **[SetOptions](#setoptions)**             | 根据键值对存储数据                                           |\r\n| remove(...)    | Preferences.remove([RemoveOptions](#removeoptions]))         | **[RemoveOptions](#removeoptions)**       | 根据键删除对应的存储项                                       |\r\n| clear()        | Preferences.clear()                                          | 无入参                                    | 清空所有存储的数据                                           |\r\n| keys()         | Preferences.keys()                                           | 无入参                                    | 获取所有存储的键名                                           |\r\n| migrate()      | Preferences.migrate()                                        | 无入参                                    | 不支持                                                       |\r\n| removeOld()    | Preferences.removeOld()                                      | 无入参                                    | 不支持                                                       |\r\n\r\n### 接口定义\r\n\r\n#### ConfigureOptions\r\n\r\n调用 `configure` 方法时的入参对象\r\n\r\n| 参数        | 类型       | 描述                                  |\r\n| ----------- | ---------- | ------------------------------------- |\r\n| group | string | 可选参数，指定存储的组名，默认为 `CapacitorStorage` |\r\n\r\n#### GetOptions\r\n\r\n调用 `get` 方法时的入参对象\r\n\r\n| 参数      | 类型       | 描述          |\r\n| --------- | ---------- | ------------- |\r\n| key | string | 必传参数，要获取的键名 |\r\n\r\n#### SetOptions\r\n\r\n调用 `set` 方法时的入参对象\r\n\r\n| 参数        | 类型       | 描述          |\r\n| ----------- | ---------- | ------------- |\r\n| key   | string | 必传参数，要设置的键名 |\r\n| value | string | 必传参数，要设置的值  |\r\n\r\n#### RemoveOptions\r\n\r\n调用 `remove` 方法时的入参对象\r\n\r\n| 参数      | 类型       | 描述          |\r\n| --------- | ---------- | ------------- |\r\n| key | string | 必传参数，要删除的键名 |\r\n\r\n## 常见问题（FAQ）\r\n\r\n### 1. 调用 get/set/remove 方法抛出「Must provide key」异常？\r\n\r\n- **原因**：`key` 是必传参数，插件原生层会严格校验，未传参、传空字符串、传 `\"null\"` 均会触发该异常。\r\n- **解决方案**：确保调用时传入合法有效的键名，格式示例：`{ key: 'myKey' }`。\r\n\r\n### 2. configure 方法的作用是什么？\r\n\r\n- **说明**：`configure` 方法用于配置 Preferences 存储选项，可以指定不同的存储组名以实现数据隔离。如果不调用 `configure` 方法，插件会使用默认的 `CapacitorStorage` 组名。\r\n\r\n## 目录结构\r\n\r\n```\r\n|---- 项目根目录\r\n|     |---- src\r\n|           |---- main\r\n|                 |---- cpp\r\n|                       |---- Preferences   # 插件核心 C++ 实现\r\n|                             |---- Preferences.h\r\n|                             |---- Preferences.cpp\r\n|                             |---- CMakeLists.txt\r\n|                 |---- ets\r\n|                       |---- components\r\n|                             |---- Preferences   # 插件核心 ArkTS 实现\r\n|                                   |---- Preferences.ets\r\n|     |---- README.md          # 说明文档\r\n|     |---- package.json       # npm 配置文件\r\n|     |---- plugin.xml         # capacitor 插件配置\r\n|     |---- LICENSE            # 许可证文件\r\n```\r\n\r\n## 贡献代码\r\n\r\n使用过程中发现任何问题都可以提 [Issue](https://gitcode.com/CPF-Ionic/capacitor-preferences/issues)，当然，也非常欢迎发 [PR](https://gitcode.com/CPF-Ionic/capacitor-preferences/pulls) 共建。\r\n\r\n## 许可证\r\n\r\n本插件基于 **MIT License** 开源，详见 [LICENSE](./LICENSE) 文件。\r\n","readmeFilename":"README.md"}