HarmonyOS 清空缓存的文档或者代码?

如题:HarmonyOS 清空缓存的文档或者代码?

阅读 559
1 个回答

清理缓存参考代码:

使用fs这个api的rmdirSync,直接删除文件即可。

清理缓存demo:

import fs from '@ohos.file.fs';
@Entry
@Component
struct Clear_cache {
  clearCache() {
    let cacheDir = getContext(this).cacheDir
    fs.listFile(cacheDir).then((filenames) => {
      for (let i = 0;i < filenames.length; i++) {
        let dirPath = `${cacheDir}/${filenames[i]}`
        // 判断是否文件夹
        let isDirectory = false
        try {
          isDirectory = fs.statSync(dirPath).isDirectory()
        }
        catch (e) {
          console.log(e)
        }
        if (isDirectory) {
          fs.rmdirSync(dirPath)
        } else {
          fs.unlink(dirPath).then(() => {
            console.info('remove file succeed');
          })
        }
      }

    })
  }
}

cacheSize包含以下几个目录,仅清理应用沙箱路径下的cache还显示有大小是正常规格。

/data/storage/el1/base/cache

/data/storage/el1/base/haps/entry/cache

/data/storage/el2/base/cache

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

获取这4个路径的方式如下:

let moduleContext: common.Context;
moduleContext = context.createModuleContext('entry');
///data/storage/el2/base/cache
let cachePathOne = moduleContext.cacheDir;
///data/storage/el2/base/haps/entry/cache
let cachePathTwo = context.cacheDir;
//切换加密等级
moduleContext.area = contextConstant.AreaMode.EL1;
///data/storage/el1/base/cache
let cachePathThree = moduleContext.cacheDir;
context.area = contextConstant.AreaMode.EL1;
///data/storage/el1/base/haps/entry/cache
let cachePathFour = context.cacheDir;
//切换回默认加密等级
moduleContext.area = contextConstant.AreaMode.EL2;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进