提交 a75b9f15 作者: 毛细亚

优化文件缓存

上级 090a6c33
module.exports = {
app_id: "wx5bf92e3883dc5a82",
game_id: "122",
binVersion:'1', // 控制bin文件缓存
/**以下参数,请勿随意修改! */
gameVersion: "1.18364"
}
\ No newline at end of file
......@@ -2,23 +2,32 @@
const ROOT_PATH=wx.env.USER_DATA_PATH
const CACHE_PATH=ROOT_PATH
const fs = wx.getFileSystemManager()
const config = require('./config/config')
let fileList = [{fileName:'mxy_release_qyppl.bin?v=5',variable:'a'}]
let promiseList = [];
function downConfig(fileInfo) {
return new Promise((resolve,rej)=>{
const {fileName,variable}=fileInfo
const {fileName,variable}=fileInfo
wx['$'+variable]={}
console.log('wx.downloadFile')
wx.downloadFile({
url: 'https://wanxiaomeng-1255977238.cos.ap-shanghai.myqcloud.com/'+fileName,
filePath: CACHE_PATH+'/'+fileName,
success: function (res) {
console.log( CACHE_PATH+'/'+fileName,'--------')
console.log('下载res:', res);
const json=fs.readFileSync(res.filePath,'utf-8')
wx['$'+variable]=JSON.parse(json)
wx.setStorage({
key:variable+'.bin',
data:JSON.stringify({binVersion:config.binVersion,binUrl:res.filePath}),
success(data){
console.log('版本号缓存成功',data)
},
fail(err){
console.log(err,'版本号缓存失败')
}
})
resolve()
console.log( wx['$'+variable])
}
});
})
......@@ -26,24 +35,74 @@ function downConfig(fileInfo) {
function checkFile(filePath){
fs.access({
path: filePath,
success(res) {
// 文件存在
return true
return new Promise((resolve,reject)=>{
fs.access({
path: filePath,
success(res) {
console.log('检测到文件存在',filePath)
// 文件存在
resolve()
},
fail(res) {
// 文件不存在或其他错误
reject()
}
})
})
}
// 先检查版本号是否相同 然后再看本地是否有已经存在的文件
function checkStorage(fileInfo){
const {variable}=fileInfo
wx.getStorage({
key:variable+'.bin',
success(res){
let data = JSON.parse(res.data)
// 缓存和配置文件版本号相同
if(res.data && data.binVersion==config.binVersion){
console.log('版本号相同',variable)
checkFile(data.binUrl).then(res=>{
console.log('文件存在',variable)
const json=fs.readFileSync(data.binUrl,'utf-8')
wx['$'+variable]=JSON.parse(json)
// console.log(wx['$'+variable])
require('./game1.js')
},err=>{
console.log('文件不存在',variable)
// 本地没有缓存文件 重新请求
requestFile()
})
}else{
console.log('版本号不同',variable)
// 版本号不同 重新请求数据
requestFile()
}
},
fail(res) {
// 文件不存在或其他错误
return false
fail(err ){
console.log('获取缓存失败',err,variable)
requestFile()
}
})
}
function requestFile(){
fileList.map((item,index)=>{
promiseList.push(downConfig(item))
})
Promise.all(promiseList).then(()=>{
console.log(wx.$a)
console.log('完成')
require('./game1.js')
})
}
var file1=downConfig({fileName:'mxy_release_qyppl.bin?v=5',variable:'a'})
fileList.map((item,index)=>{
setTimeout(() => {
checkStorage(item)
}, 300);
})
Promise.all([file1]).then(()=>{
console.log(wx.$a)
console.log('完成')
require('./game1.js')
})
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论