Skip to content

Instantly share code, notes, and snippets.

@pke
Last active September 2, 2015 23:24
Show Gist options
  • Save pke/ef337a4ca81825dd37da to your computer and use it in GitHub Desktop.
Save pke/ef337a4ca81825dd37da to your computer and use it in GitHub Desktop.
For reasons beyond my comprehension Windows.Storage.PathIO.writeTextAsync can only write to existing files, not create new ones on the fly.
writeTextAsync = (path, text) ->
# First try if an existing file can be written
Windows.Storage.PathIO.writeTextAsync(path, text)
.then null, (error) ->
[_, folder, subFolders, fileName] = /^ms-appdata:\/\/\/(temp|local|roaming)\/(.+?)\/([\w]+\.?\w+)$/.exec(path)
folder = "temporary" if folder is "temp"
createSubFolders = subFolders.split("/").reduce((promise, folderName) ->
promise = promise.then (folder) ->
folder.createFolderAsync(folderName, Windows.Storage.CreationCollisionOption.openIfExists)
, WinJS.Promise.as(Windows.Storage.ApplicationData.current["#{folder}Folder"]))
createSubFolders.then (folder) ->
folder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.openIfExists)
.then (file) ->
Windows.Storage.FileIO.writeTextAsync(file, text)
writeTextAsync("ms-appdata:///temp/apifail/file.txt", "This is how Windows.Storage.PathIO.writeTextAsync should have worked in the first place")
.done null, (error) ->
logger.error("Could not write file")
writeTextAsync = function(path, text) {
return Windows.Storage.PathIO.writeTextAsync(path, text).then(null, function(error) {
var _, createSubFolders, fileName, folder, ref, subFolders;
ref = /^ms-appdata:\/\/\/(temp|local|roaming)\/(.+?)\/([\w]+\.?\w+)$/.exec(path), _ = ref[0], folder = ref[1], subFolders = ref[2], fileName = ref[3];
if (folder === "temp") {
folder = "temporary";
}
createSubFolders = subFolders.split("/").reduce(function(promise, folderName) {
return promise = promise.then(function(folder) {
return folder.createFolderAsync(folderName, Windows.Storage.CreationCollisionOption.openIfExists);
});
}, WinJS.Promise.as(Windows.Storage.ApplicationData.current[folder + "Folder"]));
return createSubFolders.then(function(folder) {
return folder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.openIfExists);
});
}).then(function(file) {
return Windows.Storage.FileIO.writeTextAsync(file, text);
});
};
writeTextAsync("ms-appdata:///temp/apifail/file.txt", "This is how Windows.Storage.PathIO.writeTextAsync should have worked in the first place").done(null, function(error) {
return logger.error("Could not write file");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment