Reputation: 13892
I've developed a Universal App for Windows. It is deployed in my business, not through the App Store. It's perfectly functional 99.9% of the time.
But there's this one problem that's happened a couple of times.
I store persistent data in JSON format in my application local data folder.
To store my data, I use:
var storeData = function () {
return WinJS.Application.local.writeText('data', JSON.stringify(dataObject));
}
And to load my data, I use:
var loadData = function () {
return WinJS.Application.local.readText('data').then(function (text) {
dataObject = text ? JSON.parse(text) : {};
})
}
There's been a couple of cases where, during the loadData method, my app crashes. When I researched why it crashed, it turns out that there's an extra file in my local appdata folder. Obviously the file that's supposed to be there is called 'data' -- this extra file is called something like 'data-84DB.TMP' or something like that -- obviously a temporary file created as part of the file io API. In these cases where my app is crashing, this file has the information in it that you'd normally expect to see in the 'data' file, and the 'data' file is no longer in text format and when I open it in SublimeText it says '0000'.
So when my loadData function runs, it crashes.
Now, this is not a situation in which I want it to fail silently. I'd rather it crash than, say, just do a try-catch in loadData and make my dataObject empty or something in the cases where the data didn't save right. I'd rather it crash, so that then at least I can go and find the .TMP file and restore the information that didn't properly save.
Is this problem normal? Am I not following best practices for reading and writing persistent data? How can I fix this issue? Do you guys know what causes it? Might it be that the app unexpectedly shuts down in the middle of a file-writing operation?
Upvotes: 0
Views: 185
Reputation: 241
I think the best practice should be to do reads and saves asynchronously. I guess WinJS.Application.local
is a wrapper for WinRT API, but it works synchronously. I would suggest to use Windows.Storage.FileIO.writeTextAsync
and Windows.Storage.FileIO.readTextAsync
.
Also I found out that JSON.parse
crashes (throws an error) when the string to parse is empty (""). In your case I see that it can be a problem as well since you're testing only if it's null or undefined, not if it's empty.
Upvotes: 1