Metro Style App HTML/JS writing local files

。_饼干妹妹 提交于 2019-12-06 22:03:38
devhammer

The question of whether it's a "bad idea" is quite subjective, so probably not the right venue for that.

However, in terms of how Windows Store apps treat files you store, if you create and/or edit files using Windows.Storage.ApplicationData.current.localFolder, these files will be available until the user uninstalls the app. If you push an update of your app to the store, and the user downloads and installs the update, the files will remain on the user's machine, unless you explicitly modify them programmatically.

In two apps that I've built, I leverage the localFolder to store JSON representations of the app's data so that I can minimize startup time, and refresh the data in the background once the app has started up and rendered its initial UI to the user.

Here's what my code (which could probably be optimized a bit) looks like:

appData.current.localFolder.createFileAsync("leaderboard.txt", 
    Windows.Storage.CreationCollisionOption.openIfExists)
.then(function (file) {
    leaderboardFile = file;
    return Windows.Storage.FileIO.readTextAsync(file)
})
.then(function (fileContents) {
    cachedLeaderboard = fileContents;
    if (!cachedLeaderboard || isRefresh) {
        return WinJS.xhr(xhrOptions)
    }
    else {
        cachedLeaderboard = JSON.parse(cachedLeaderboard);
        List = new WinJS.Binding.List(cachedLeaderboard);
        completed(List);
    }
})
.then(function (result) {
    if (result) {
       var items = JSON.parse(result.responseText).d;
       localLeaderboard = items;
       return Windows.Storage.FileIO.writeTextAsync(leaderboardFile, 
           JSON.stringify(localLeaderboard))
    }
})
.then(function () {
    if (!localLeaderboard)
    localLeaderboard = cachedLeaderboard;
    List = new WinJS.Binding.List(localLeaderboard);
    completed(List);
})

Basically, the code will check whether the leaderboard.txt file exists (or if the call is a refresh of the data), and if not, make an XHR call to get the data, then create a binding list and pass it back to the caller wrapped in a promise (the promise code isn't shown). If the file exists, and the request isn't a refresh, I just parse the text file and create the binding list from that.

Hope that helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!