Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
* Attach a writeTextToFile method to cordova.file API.
*
* params = {
* text: 'Text to go into the file.',
* path: 'file://path/to/directory',
* fileName: 'name-of-the-file.txt',
* append: false
* }
*
* callback = {
* success: function(file) {},
* error: function(error) {}
* }
*
*/
cordova.file.writeTextToFile = function(params, callback) {
window.resolveLocalFileSystemURL(params.path, function(dir) {
dir.getFile(params.fileName, {create:true}, function(file) {
if(!file) return callback.error('dir.getFile failed')
file.createWriter(
function(fileWriter) {
if (params.append == true) fileWriter.seek(fileWriter.length)
var blob = new Blob([params.text], {type:'text/plain'})
fileWriter.write(blob)
callback.success(file)
},
function(error) {
callback.error(error)
}
)
})
})
}
/*
* Use the writeTextToFile method.
*/
cordova.file.writeTextToFile({
text: 'The date is ' + (new Date()),
path: cordova.file.externalDataDirectory,
fileName: 'example-file.txt',
append: false
},
{
success: function(file) {
console.log("Success! Look for the file at " + file.nativeURL)
console.log(file)
},
error: function(error) {
console.log(error)
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment