Skip to content

Instantly share code, notes, and snippets.

@smurfpandey
Created March 3, 2017 10:53
Show Gist options
  • Save smurfpandey/e7b6345c5e7914d3b64080958d7306c9 to your computer and use it in GitHub Desktop.
Save smurfpandey/e7b6345c5e7914d3b64080958d7306c9 to your computer and use it in GitHub Desktop.
Write data to file using cordova file plugin. This snippet uses promise using q.js
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