Cordova File Plugin ignore my folder and files - javascript

I'm trying read a file (example.json) inside www/usr/ folder, but I'm having some problems, to try see what is happening I decide list the files and folders inside of www/, and surprise, my usr/ folder is not listed, just default folder as js/, css/, img/, etc...
This code list the folders:
document.addEventListener('deviceready', function () {
window.resolveLocalFileSystemURL(
cordova.file.applicationDirectory + 'www/',
function (dirEntry) {
// list folders
function success(entries) {
var i;
alert(entries.length > 0);
for (i=0; i<entries.length; i++) {
alert(entries[i].name);
}
}
var directoryReader = dirEntry.createReader();
directoryReader.readEntries(success,self.error);
},
self.error
);
});
And this try get the file:
document.addEventListener('deviceready', function () {
window.resolveLocalFileSystemURL(
cordova.file.applicationDirectory + 'www/usr/',
function (dirEntry) {
dirEntry.getFile(
'example.json',
{create: false, exclusive: false},
function (fileEntry) {
alert('ok');
},
self.error
);
},
self.error
);
});
Did I do someting wrong?

Does the usr folder contain data already or are you trying to read a file that the app is creating at runtime?

Related

how to create or write a file in android on phonegap?

I am using below code to write a file on android using PhoneGap, I think that this line window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) { is giving the error, can't find the exact error, just because I can't debug on android.
I find PhoneGap documentation confusing.
function download_file(cur_filename)
{
alert(5);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
alert(2);
console.log('file system open: ' + fs.name);
alert(3);
fs.root.getFile(cur_filename, { create: true, exclusive: false }, function (fileEntry) {
alert("fileEntry is file?" + fileEntry.isFile.toString());
// fileEntry.name == 'someFile.txt'
fileEntry.name==cur_filename;
// fileEntry.fullPath == '/someFile.txt'
writeFile(fileEntry, null);
}, onErrorCreateFile);
}, onErrorLoadFs);
}
function writeFile(fileEntry, dataObj) {
aler(4);
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file write...");
readFile(fileEntry);
};
fileWriter.onerror = function (e) {
console.log("Failed file write: " + e.toString());
};
// If data object is not passed in,
// create a new Blob instead.
if (!dataObj) {
dataObj = new Blob(['some file data'], { type: 'text/plain' });
}
fileWriter.write(dataObj);
});
}
Firstly, you can directly download the file rather than having to create and write a new one. You need to first install the following plugins
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-file-transfer
Now, you need to enclose the below logic inside deviceready event in case you are accessing plugins on app launch. The file-transfer ships with a download() that you need to use for downloading your file. Please find a sample code below
document.addEventListener("deviceready", startDownload, false);
function startDownload() {
var fileTransfer = new FileTransfer();
// replace uri with -> http://192.168.43.54/text.csv
var uri = encodeURI("https://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_1920_18MG.mp4");
fileTransfer.download(
uri,
cordova.file.dataDirectory + 'videos/big_buck_bunny_720p_1mb.mp4',
function(entry) {
console.log("download complete: ", entry);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code" + error.code);
}
);
}
Once the download is completed, the entry object will have a nativeURL property that holds the local URL to the file.
More info
File Plugin
File-Transfer Download

gulp-task output in console is not printing expected result

I have the following gulp task which inserts .css and .js files in the html file:
gulp.task('inject', function () {
log('Injecting the JS and CSS files into index.html');
var wiredep = require('wiredep').stream;
var options = config.getWiredepDefaultOptions();
return gulp.src(config.index)
.pipe(wiredep(options))
.pipe($.inject(gulp.src(config.customFiles), {ignorePath: options.ignorePath}))
.pipe(gulp.dest(config.client));
});
and my gulp.config.js:
module.exports = function () {
var client = './public';
var config = {
allJS: [
'*.js',
'public/js/*.js',
'public/js/**/*.js'
],
client: client,
index: client + '/index.html',
customFiles: [
'./public/css/*.css',
'./public/js/*.js',
'./public/js/**/*.js'
],
bower: {
json: require('./bower.json'),
directory: './public/lib',
ignorePath: '/public/'
},
};
config.getWiredepDefaultOptions = function () {
var options = {
bowerJson: config.bower.json,
directory: config.bower.directory,
ignorePath: config.bower.ignorePath
};
return options;
};
return config;
};
This works as expected, but when I run the task I get this:
It always says gulp-inject 3 files into index.html, even though no new files was added.
Is there something wrong with my gulp file?
Well if you are using gulp-inject this is what I found.
If you look at the code in gulp-inject you can see it just spits out the file count unless it gets opt.quiet set. I didn't see a option in the docs for this setting but if you look at the tests it shows an example it being used.
Enabling quiet mode link line 505
inject(sources, {quiet: true});
Source where it generates the log statement. link line 109
function getNewContent(target, collection, opt) {
var logger = opt.quiet ? noop : function (filesCount) {
if (filesCount) {
log(cyan(filesCount) + ' files into ' + magenta(target.relative) + '.');
} else {
log('Nothing to inject into ' + magenta(target.relative) + '.');
}
};

Image File Download issue in ionic for iOS platform

I am trying to download some image files and store it for offline accessibility purpose of the app using Ionic framework. I have used two Cordova plugins named "Cordova-plugin-file" and "Cordova-plugin-file transfer". My code works on Android but faces a strange issue in iOS platform.
Error in Success callbackId: FileTransfer552364304 : TypeError: null
is not an object (evaluating 'result.lengthComputable'),
callbackFromNativecordova.js
Sometimes the code works, sometimes it throws me this error. Also I cannot access the error from my javascript code. Can anyone help? The code snippet is given below:
downloadImage: function(url, fileName) {
var deferred = $q.defer();
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getDirectory(
LOCAL_STORAGE_KEYS.app, {
create: true
},
function(dirEntry) {
// console.log(arguments);
dirEntry.getFile(
fileName, {
create: true,
exclusive: false
},
function(fe) {
console.log(arguments);
var p = fe.toURL();
console.log("In service the url path:", p);
fe.remove();
var ft = new FileTransfer();
console.log('File Transfer instance:',ft);
ft.download(
encodeURI(url),
p,
function(entry) {
console.log('In service the entry callback:',entry);
if (entry && entry.toURL) {
deferred.resolve(entry.toURL());
} else {
deferred.resolve();
}
},
function(err) {
console.log('Getting rejected:',err);
deferred.reject(err);
},
false,
null
);
},
function() {
deferred.reject(new Error('get file failed'));
}
);
}
);
},
function() {
deferred.reject(new Error('get directory failed'));
});
return deferred.promise;
}

phonegap deleting a file within a sub folder

I want to deleate a file in phonegap android application.
file is exists in subfolder.
I am finding a sample code on the internet.But I can't see.
Phonegap docs
is not enough for me.Can someone answer me how to delete a file within a subfolder.
function deleteFilelists(tx,results)
{
var fileName = "cdvfile://localhost/persistent//flower.jpg"
removefile(fileName);
function removefile(fileName){
fileSystem.root.getFile(fileName, {create: false, exclusive: false}, gotRemoveFileEntry, fail);
}
function gotRemoveFileEntry(fileEntry){
fileEntry.remove(success, fail);
}
function success(entry) {
alert("Removal succeeded");
}
function fail(error) {
alert("Error removing file: " + error.code);
}
}

Persistent storage in Phonegap

I have literally spent the last 6 hours trying to persist data using phonegap, my first approach was using the localStorate API but that was killed everytime the app restarted so it was useless. Now I implemented it by writing a file to the the filesystem, but with the following problems:
The file is created ok
The file has the corrent content doing adb pull /data/data/[package name]/friends.txt) I can see the content of the file
But trying to read from it I always get NULL.
This is my code if anyone can help me... I am out of ideas now :(
var friends = [];
// Initialize the Facebook SDK
document.addEventListener('deviceready', function() {
FB.init({
appId: '[myAppID]',
nativeInterface: CDV.FB,
useCachedDialogs: false
});
// Check if we already fetched our friends
readSavedContent();
});
function readSavedContent() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystemForRead, fail);
}
function gotFileSystemForRead(fileSystem) {
fileSystem.root.getFile("friends.txt", {create: true, exclusive: false}, gotFileEntryForRead, fail);
}
function gotFileSystemForWrite(fileSystem) {
fileSystem.root.getFile("friends.txt", {create: true, exclusive: false}, gotFileEntryForWrite, fail);
}
function gotFileEntryForRead(fileEntry) {
var reader = new FileReader();
reader.onloadend = function(evt) {
alert("Data stored is " + evt.target.result);
};
reader.readAsText(fileEntry);
}
function gotFileEntryForWrite(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
// show a message
alert(friends.length + " friends fetched, you should be able to see them if you restart the app");
};
writer.write(JSON.stringify(friends));
}
function fail(error) {
console.log(error.code);
alert(error);
}
function login() {
FB.login(function (response) {
console.log(JSON.stringify(response));
if (response.status === "connected") {
alert("logged in: fetching friends now");
// Fetch my friends
FB.api("/fql?q=" + encodeURIComponent('SELECT uid, first_name, last_name, email, pic, pic_big, is_app_user, devices FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1= me()) ORDER BY first_name LIMIT 2000'),
function(response) {
friends = response.data;
// Store the data to the disk
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystemForWrite, fail);
}
);
} else {
alert('not logged in');
}
}, {
scope: "email"
});
}
From what I can see you have forgotten one step during the file read operation.
In your case you have this order:
function gotFileSystemForRead(fileSystem) {
fileSystem.root.getFile("friends.txt", {create: true, exclusive: false}, gotFileEntryForRead, fail);
}
function gotFileEntryForRead(fileEntry) {
var reader = new FileReader();
reader.onloadend = function(evt) {
alert("Data stored is " + evt.target.result);
};
reader.readAsText(fileEntry);
}
When it should look like this:
function gotFileSystemForRead(fileSystem) {
fileSystem.root.getFile("friends.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFileEntryForRead, fail);
}
function gotFileEntryForRead(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
alert("Data stored is " + evt.target.result);
};
reader.readAsText(file);
}
To find out more take a look at this official Phonegape FileReader documentation.
Then again you can always abandon this solution and use a persistance js for data storage. It will provide you 4+1 different options for file/data storage and it works on numerous platforms.
As a side note, localstorage persistence was bugged in cordova(phonegap) version 2.6, so if this is your case, try migrating to cordova 2.7 recently released or downgrade to 2.5 to get rid of said bug.

Categories

Resources