uni-app得知缓存字节数目及清理缓存的办法
Le Sun 23 February 2025
姑娘有自己的cache_helper.js。
function human_readable_size(bytes, decimals = 2) {
if (!Number(bytes)) {
return '0 Bytes';
}
const kbToBytes = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = [
'Bytes',
'KiB',
'MiB',
'GiB',
'TiB',
'PiB',
'EiB',
'ZiB',
'YiB',
];
const index = Math.floor(
Math.log(bytes) / Math.log(kbToBytes),
);
return `${parseFloat(
(bytes / Math.pow(kbToBytes, index)).toFixed(dm),
)} ${sizes[index]}`;
}
function size_cached(cb) {
uni.getStorageInfo({
success: function({
currentSize
}) {
cb(human_readable_size(currentSize))
},
fail: function() {
cb("无法获取缓存信息")
}
})
}
function cache_clean() {
uni.showModal({
title: '提示',
content: '您确定要清除缓存吗?',
confirmText: '立即清除',
success: function({
confirm
}) {
if (confirm) {
uni.clearStorageSync()
uni.showToast({
title: "缓存已经成功清理"
})
}
}
})
}
export {
size_cached,
cache_clean
}