HarmonyOS 鸿蒙Next【小白请教】第一次使用DevEcoStudio开发纯JS应用,如何读写本地数据呢
HarmonyOS 鸿蒙Next【小白请教】第一次使用DevEcoStudio开发纯JS应用,如何读写本地数据呢 求助各位大佬我应该使用哪些接口呢?如何使用?直接用网上搜的require函数貌似DevEcoStudio这边不支持
[@ohos.file.fs (文件管理)-文件管理-ArkTS接口参考-ArkTS API参考-HarmonyOS应用开发](https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/js-apis-file-fs-0000001451843016-V3#ZH-CN_TOPIC_0000001574088233__fsread)
更多关于HarmonyOS 鸿蒙Next【小白请教】第一次使用DevEcoStudio开发纯JS应用,如何读写本地数据呢的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
[@ohos.file.fs (文件管理)](https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/js-apis-file-fs-0000001451843016-V3#ZH-CN_TOPIC_0000001574088233__fsread).readText()方法:它的返回值是Promise类型,我应该如何获取文件的文本内容呢?按照示例代码调用:
let filePath = "/common/images/aa.text";
fs.readText(filePath).then((str) => {
console.log("readText succeed:" + str);
}).catch((err) => {
console.info("readText failed with error message: " + err.message + ", error code: " + err.code);
});
结果日志显示以下信息:
fileIo.readText interface mocked in the Previewer. How this interface works on the Previewer may be different from that on a real device.
01-16 22:40:42.730 I A0c0d0/JSApp: app Log: readText succeed:[PC Preview] unknow boolean
求问如何解决这个问题,如何才能拿到文本内容?感谢
在HarmonyOS中使用DevEco Studio开发纯JS应用时,读写本地数据可以通过@ohos.data.storage模块实现。首先,在entry/src/main/js/default/pages/index/index.js中导入storage模块:
import storage from '@ohos.data.storage';
接下来,可以通过storage.getStorageSync方法获取Storage实例,并使用put和get方法进行数据读写。例如:
let storage = storage.getStorageSync('/data/storage/el2/base/local');
storage.putSync('key', 'value');
let value = storage.getSync('key', 'default');
以上代码实现了将'value'写入'key',并从'key'中读取数据。如果'key'不存在,则返回'default'。
此外,可以使用delete方法删除数据,使用clear方法清空所有数据:
storage.deleteSync('key');
storage.clearSync();
最后,不要忘记在config.json中声明ohos.permission.WRITE_USER_STORAGE和ohos.permission.READ_USER_STORAGE权限:
"reqPermissions": [
{
"name": "ohos.permission.WRITE_USER_STORAGE"
},
{
"name": "ohos.permission.READ_USER_STORAGE"
}
]
这样即可在鸿蒙Next中实现纯JS应用的本地数据读写。

