Created
March 3, 2017 10:52
-
-
Save smurfpandey/d28ff866207bacedc3ee94cdabe3a2c0 to your computer and use it in GitHub Desktop.
Write data to file using cordova file plugin.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fnCreateDirectoryInFileSystem = function (rootPath, newFolderName) { | |
var deferred = Q.defer(); | |
var fnDirFail = function (err) { | |
//Root path missing | |
deferred.reject(); | |
}; | |
var fnGotDir = function (dirEntry) { | |
//Create the first directory | |
dirEntry.getDirectory(newFolderName, { | |
create: true, | |
exclusive: false | |
}, function () { | |
deferred.resolve({ | |
data: rootPath + '/' + newFolderName | |
}); | |
}, fnDirFail); | |
}; | |
window.resolveLocalFileSystemURL(rootPath, fnGotDir, fnDirFail); | |
return deferred.promise; | |
}; | |
var fnWriteToFileSystem = function (fileName, fileData) { | |
var deferred = Q.defer(); | |
var rootPath = cordova.file.dataDirectory; | |
var dirPath = rootPath + 'my-dir'; | |
var fnFail = function (err) { | |
deferred.reject(err); | |
}; | |
var _fnWriter = function (dirEntry) { | |
var gotFileWriter = function (writer) { | |
writer.onwrite = function (evt) { | |
deferred.resolve({ | |
data: evt | |
}); | |
}; | |
writer.write(fileData); | |
} | |
var fnGotFile = function (fileEntry) { | |
fileEntry.createWriter(gotFileWriter, fnFail); | |
} | |
dirEntry.getFile(relativePath, { | |
create: true, | |
exclusive: false | |
}, fnGotFile, fnFail); | |
}; | |
var fnCreateDir = function () { | |
fnCreateDirectoryInFileSystem(rootPath, 'my-dir').then(function (data) { | |
var dirPath = data.data; | |
window.resolveLocalFileSystemURL(dirPath, _fnWriter, fnFail); | |
}); | |
} | |
//Check if dirPath exists | |
window.resolveLocalFileSystemURL(dirPath, _fnWriter, fnCreateDir); | |
return deferred.promise; | |
} | |
document.addEventListener('deviceready', function(e){ | |
fnWriteToFileSystem('mydata.txt', 'ABC PQR MNO'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment