how to append to file with cordova-plugin-file - javascript

I'm trying to append text to a file.
I have followed tutorial of Html5rocks as suggested by plugins's github page.
I've sucessfully created a file and wrote to it. But when im trying to append text, i got a write success event but no text is added. I'm only able to change characters but no characted added to the end. It's not an async issue, i'm also trying live test with chrome's js console. Im also using fileWriter.seek(fileWriter.length) before trying to write at the end. (but seek(0) to write a the beginning)
there is the module i wrote :
'use strict';
function File_mgmt(name) {
var name = name;
var myfile = '';
var next_write = '';
var that = this;
var errorHandler = function (e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
console.log('Error: ' + msg);
};
var init = function() {
console.log("init");
request(gotFS);
};
var gotFS = function() {
console.log("gotfs");
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
dir.getFile(name, {create:true}, function(file) {
myfile = file;
}, errorHandler);
});
};
this.write = function (data) {
myfile.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
fileWriter.seek(fileWriter.length);
fileWriter.write(data);
}, errorHandler);
};
this.reopen = function() {
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
dir.getFile(name, {create:false}, function(file) {
myfile = file;
}, errorHandler);
});
};
this.getfile = function() {
return myfile;
};
this.writeTextBlob = function(data) {
this.write(new Blob([data], {type: 'text/plain'}));
};
var request = function(success){
var fail = function() {console.log("failed to initialise system")};
window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024*1024, success, fail);
};
var writer = function() {
myfile.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
fileWriter.seek(fileWriter.length);
fileWriter.write(next_write);
}, errorHandler);
};
this.testWrite = function(data) {
next_write = data;
request(writer);
};
init();
return this;
}
I'm using it with chrome console with
var f = new File_mgmt("test");
f.writeTextBlob("test1");
f.writeTextBlob("test2");
Edit
I've tried to pass by a window.requestFileSystem() to append but it still doesnt work, I've also updated my code.
now i'm doing
var f = new File_mgmt("test");
f.testWrite("test1");
f.testWrite("test2");

It's appearing than my file actually got new data. I had to unplugged then replugged usb cable to see the new data appened to my file.
May be it's a problem with Windows. I'll look if i got the same problem on linux.

Related

Send object id from success function to another function in parse.com

I have a problem on parse.com in which i to take the id of an type and pass it to another function which uploads an image. Then take the type.id among with the image and post it to another function which saves the data to a class.
This is what i've tried until now without success.
--OnClick code
$('#submitId').on("click", function(e, f) {
e.preventDefault();
typeSave(typeid1);
//var objnew1 = typeSave();
console.log("inside onclick " + type2);
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
parseFile.save().then(
function() {
//typeSave();
type2 = typeid1;
saveJobApp(parseFile, type2);
console.log("inside save onclick " + type2);
},
function(error) {
alert("error");
}
);
});
-- Type Code
var type;
var typeid1;
var type2;
function typeSave() {
var type = new Parse.Object("type");
var user = new Parse.Object("magazia");
//var bID = objbID;
//user.id = bID;
var cafebar = document.getElementById('cafe_bar').checked;
if (cafebar) {
var valueCafebar = true;
} else {
var valueCafebar = false;
}
var club = document.getElementById('club').checked;
if (club) {
var valueClub = true;
} else {
var valueClub = false;
}
var restaurant = document.getElementById('restaurant').checked;
if (restaurant) {
var valueRestaurant = true;
} else {
var valueRestaurant = false;
}
var pistes = document.getElementById('pistes').checked;
if (pistes) {
var valuePistes = true;
} else {
var valuePistes = false;
}
type.set("cafebar", valueCafebar);
type.set("club", valueClub);
type.set("restaurant", valueRestaurant);
type.set("pistes", valuePistes);
type.save(null, {
success: function(type) {
//saveJobApp(type.id);
var typeid1 = type.id;
console.log("inside type save " + typeid1);
//return ;
},
error: function(type, error) {
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
-- Send Data to parse.com class code
function saveJobApp(objParseFile, type2) {
var jobApplication = new Parse.Object("magazia");
var email = document.getElementById('email').value;
var name = document.getElementById('name').value;
var description = document.getElementById('description').value;
var website = document.getElementById('website').value;
var phone = document.getElementById('phone').value;
var address = document.getElementById('address').value;
var latlon = document.getElementById('latlon').value;
var area = document.getElementById('area').value;
var value = latlon;
value = value.replace(/[\(\)]/g, '').split(', ');
console.log("inside saveJobApp " + type2);
var x = parseFloat(value[0]);
var y = parseFloat(value[1]);
var point = new Parse.GeoPoint(x, y);
jobApplication.set("image", objParseFile);
jobApplication.set("email", email);
jobApplication.set("phone", phone);
jobApplication.set("address", address);
jobApplication.set("name", name);
jobApplication.set("website", website);
jobApplication.set("description", description);
jobApplication.set("area", area);
jobApplication.set("latlon", point);
jobApplication.set("typeID", type2);
jobApplication.save(null, {
success: function(gameScore) {
// typeSave(jobApplication.id);
},
error: function(gameScore, error) {
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
So resuming i am trying when i click the button to first run the typesave() function, after when it posts the type on the type class in parse, to take to type.id from the success function and send it to the parseFile.save().then
and then to send the objectFile and the type2 (which is the type.id) it in saveJobApp and them to save it in class magazia
What i get from the console.logs is this
Which means that my code post to the type class and takes the type.id
but it doesnt send it to the magazia class via the parsefile save.
Any idea of what am i missing?
I noticed your mistake is not about the functions but about trying to pass the type.id as a string and not as a function in the saveJobApp function.
if you try making it like this
function saveJobApp(objParseFile , objtype) {
var jobApplication = new Parse.Object("magazia");
var type = new Parse.Object("type");
type.id = objtype;
jobApplication.set("typeID", type);
I think it will work.
And also update the onclick and the ParseFile save code to this
$('#submitId').on("click", function(e) {
typeSave();
});
function PhotoUpload(objtype){
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
parseFile.save().then(
function() {
saveJobApp(parseFile, objtype);
},
function(error) {
alert("error");
}
);
}
And the success function in typeSave()
should be something like this
type.save(null, {
success: function(type) {
PhotoUpload(type.id);
},
Hope this helps :)

How i can externalize a function from a prototype in javascript

I'm trying to hack/personalize a html5/ajax/javascript plugin for drag&drop and upload a file
(the problem with this plugin is that it uploads the file directly after being dropped on the drop zone..) So i want to change this behaviour and control the moment in which the upload should happens
(the upload uses jquery-ajax) by externalizing the upload function
The main plugin's script is written in this page (the html5Upload.js) :
/*jslint unparam: true, browser: true, devel: true */
/*global define*/
define(function () {
'use strict';
var module = {},
noop = function () { },
console = window.console || { log: noop },
supportsFileApi;
function UploadManager(options) {
var self = this;
self.dropContainer = options.dropContainer;
self.inputField = options.inputField;
self.uploadsQueue = [];
self.activeUploads = 0;
self.data = options.data;
self.key = options.key;
self.maxSimultaneousUploads = options.maxSimultaneousUploads || -1;
self.onFileAdded = options.onFileAdded || noop;
self.uploadUrl = options.uploadUrl;
self.onFileAddedProxy = function (upload) {
console.log('Event: onFileAdded, file: ' + upload.fileName);
self.onFileAdded(upload);
};
self.initialize();
}
function FileUpload(file) {
var self = this;
self.file = file;
self.fileName = file.name;
self.fileSize = file.size;
self.uploadSize = file.size;
self.uploadedBytes = 0;
self.eventHandlers = {};
self.events = {
onProgress: function (fileSize, uploadedBytes) {
var progress = uploadedBytes / fileSize * 100;
console.log('Event: upload onProgress, progress = ' + progress + ', fileSize = ' + fileSize + ', uploadedBytes = ' + uploadedBytes);
(self.eventHandlers.onProgress || noop)(progress, fileSize, uploadedBytes);
},
onStart: function () {
console.log('Event: upload onStart');
(self.eventHandlers.onStart || noop)();
},
onCompleted: function (data) {
console.log('Event: upload onCompleted, data = ' + data);
file = null;
(self.eventHandlers.onCompleted || noop)(data);
}
};
}
FileUpload.prototype = {
on: function (eventHandlers) {
this.eventHandlers = eventHandlers;
}
};
UploadManager.prototype = {
initialize: function () {
console.log('Initializing upload manager');
var manager = this,
dropContainer = manager.dropContainer,
inputField = manager.inputField,
cancelEvent = function (e) {
e.preventDefault();
e.stopPropagation();
};
if (dropContainer) {
manager.on(dropContainer, 'dragover', cancelEvent);
manager.on(dropContainer, 'dragenter', cancelEvent);
manager.on(dropContainer, 'drop', function (e) {
cancelEvent(e);
manager.processFiles(e.dataTransfer.files);
});
}
if (inputField) {
manager.on(inputField, 'change', function () {
manager.processFiles(this.files);
});
}
},
processFiles: function (files) {
console.log('Processing files: ' + files.length);
var manager = this,
len = files.length,
file,
upload,
i;
for (i = 0; i < len; i += 1) {
file = files[i];
if (file.size === 0) {
alert('Files with files size zero cannot be uploaded or multiple file uploads are not supported by your browser');
break;
}
upload = new FileUpload(file);
manager.uploadFile(upload);
}
},
uploadFile: function (upload) {
var manager = this;
manager.onFileAdded(upload);
// Queue upload if maximum simultaneous uploads reached:
if (manager.activeUploads === manager.maxSimultaneousUploads) {
console.log('Queue upload: ' + upload.fileName);
manager.uploadsQueue.push(upload);
return;
}
manager.ajaxUpload(upload);
},
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This is the function i want to externalize to be called from outside this script
ajaxUpload: function (upload) {
var manager = this,
xhr,
formData,
fileName,
file = upload.file,
prop,
data = manager.data,
key = manager.key || 'file';
console.log('Beging upload: ' + upload.fileName);
manager.activeUploads += 1;
xhr = new window.XMLHttpRequest();
formData = new window.FormData();
fileName = file.name;
xhr.open('POST', manager.uploadUrl);
// Triggered when upload starts:
xhr.upload.onloadstart = function () {
// File size is not reported during start!
console.log('Upload started: ' + fileName);
upload.events.onStart();
};
// Triggered many times during upload:
xhr.upload.onprogress = function (event) {
if (!event.lengthComputable) {
return;
}
// Update file size because it might be bigger than reported by the fileSize:
upload.events.onProgress(event.total, event.loaded);
};
// Triggered when upload is completed:
xhr.onload = function (event) {
console.log('Upload completed: ' + fileName);
// Reduce number of active uploads:
manager.activeUploads -= 1;
upload.events.onCompleted(event.target.responseText);
// Check if there are any uploads left in a queue:
if (manager.uploadsQueue.length) {
manager.ajaxUpload(manager.uploadsQueue.shift());
}
};
// Triggered when upload fails:
xhr.onerror = function () {
console.log('Upload failed: ', upload.fileName);
};
// Append additional data if provided:
if (data) {
for (prop in data) {
if (data.hasOwnProperty(prop)) {
console.log('Adding data: ' + prop + ' = ' + data[prop]);
formData.append(prop, data[prop]);
}
}
}
// Append file data:
formData.append(key, file);
// Initiate upload:
xhr.send(formData);
},
on: function (element, eventName, handler) {
if (!element) {
return;
}
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + eventName, handler);
} else {
element['on' + eventName] = handler;
}
}
};
module.fileApiSupported = function () {
if (typeof supportsFileApi !== 'boolean') {
var input = document.createElement("input");
input.setAttribute("type", "file");
supportsFileApi = !!input.files;
}
return supportsFileApi;
};
module.initialize = function (options) {
return new UploadManager(options);
};
return module;
});
i was thinking about to set the scope of all variables needed by that function to the global scope
and define it outside the prototype .. i'm not sure it will work as this function calls the manager to which it belongs itself..
honnestly, i'm not that expert to make this work , i hope your help guys
Simply set it to where it returns whatever it is you need in the global scope. For example,
Instead of:
return module;
Do:
return {
module: module,
fileUpload: FileUpload };
You could take the text define and replace it with var uploader = this will give you an object with all of the characteristics and methods including the one you are looking to extract. Now if this code is relying on some other externally defined object it might through some errors but a basic reading of the code doesn't appear to rely on anything. I would not change the scope of the variables or attempt to cut out one (or even a few) methods. JavaScript closures make removing arbitrary code much harder.
As i said, setting the variables's scope needed by the function to the global scope
var monmanager;
var monupload;
/////////////////////////////////////////////////////////////////////////////////////
/*jslint unparam: true, browser: true, devel: true */
/*global define*/
define(function () {
'use strict';
var module = {},
noop = function () { },
console = window.console || { log: noop },
supportsFileApi;
function UploadManager(options) {
var self = this;
self.dropContainer = options.dropContainer;
self.inputField = options.inputField;
self.uploadsQueue = [];
self.activeUploads = 0;
self.data = options.data;
self.key = options.key;
self.maxSimultaneousUploads = options.maxSimultaneousUploads || -1;
self.onFileAdded = options.onFileAdded || noop;
self.uploadUrl = options.uploadUrl;
self.onFileAddedProxy = function (upload) {
console.log('Event: onFileAdded, file: ' + upload.fileName);
self.onFileAdded(upload);
};
self.initialize();
}
function FileUpload(file) {
var self = this;
self.file = file;
self.fileName = file.name;
self.fileSize = file.size;
self.uploadSize = file.size;
self.uploadedBytes = 0;
self.eventHandlers = {};
self.events = {
onProgress: function (fileSize, uploadedBytes) {
var progress = uploadedBytes / fileSize * 100;
console.log('Event: upload onProgress, progress = ' + progress + ', fileSize = ' + fileSize + ', uploadedBytes = ' + uploadedBytes);
(self.eventHandlers.onProgress || noop)(progress, fileSize, uploadedBytes);
},
onStart: function () {
console.log('Event: upload onStart');
(self.eventHandlers.onStart || noop)();
},
onCompleted: function (data) {
console.log('Event: upload onCompleted, data = ' + data);
file = null;
(self.eventHandlers.onCompleted || noop)(data);
}
};
}
FileUpload.prototype = {
on: function (eventHandlers) {
this.eventHandlers = eventHandlers;
}
};
UploadManager.prototype = {
initialize: function () {
console.log('Initializing upload manager');
var manager = this,
dropContainer = manager.dropContainer,
inputField = manager.inputField,
cancelEvent = function (e) {
e.preventDefault();
e.stopPropagation();
};
if (dropContainer) {
manager.on(dropContainer, 'dragover', cancelEvent);
manager.on(dropContainer, 'dragenter', cancelEvent);
manager.on(dropContainer, 'drop', function (e) {
cancelEvent(e);
manager.processFiles(e.dataTransfer.files);
});
}
if (inputField) {
manager.on(inputField, 'change', function () {
manager.processFiles(this.files);
});
}
},
processFiles: function (files) {
console.log('Processing files: ' + files.length);
var manager = this,
len = files.length,
file,
upload,
i;
for (i = 0; i < len; i += 1) {
file = files[i];
if (file.size === 0) {
alert('Files with files size zero cannot be uploaded or multiple file uploads are not supported by your browser');
break;
}
upload = new FileUpload(file);
manager.uploadFile(upload);
}
},
uploadFile: function (upload) {
var manager = this;
//////////my modification////////////////-----------------------------------------<<<<<<<<<<<<<<<
monmanager = manager;
//////////////////////////-----------------------------------------<<<<<<<<<<<<<<<
manager.onFileAdded(upload);
// Queue upload if maximum simultaneous uploads reached:
if (manager.activeUploads === manager.maxSimultaneousUploads) {
console.log('Queue upload: ' + upload.fileName);
manager.uploadsQueue.push(upload);
return;
}
//////////my modification////////////////-----------------------------------------<<<<<<<<<<<<<<<
monupload = upload;
//////////////////////////-----------------------------------------<<<<<<<<<<<<<<<
// manager.ajaxUpload(upload);
},
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This is the function i want to externalize to be called from outside this script
ajaxUpload: function (upload) {
var manager = this,
xhr,
formData,
fileName,
file = upload.file,
prop,
data = manager.data,
key = manager.key || 'file';
console.log('Beging upload: ' + upload.fileName);
manager.activeUploads += 1;
xhr = new window.XMLHttpRequest();
formData = new window.FormData();
fileName = file.name;
xhr.open('POST', manager.uploadUrl);
// Triggered when upload starts:
xhr.upload.onloadstart = function () {
// File size is not reported during start!
console.log('Upload started: ' + fileName);
upload.events.onStart();
};
// Triggered many times during upload:
xhr.upload.onprogress = function (event) {
if (!event.lengthComputable) {
return;
}
// Update file size because it might be bigger than reported by the fileSize:
upload.events.onProgress(event.total, event.loaded);
};
// Triggered when upload is completed:
xhr.onload = function (event) {
console.log('Upload completed: ' + fileName);
// Reduce number of active uploads:
manager.activeUploads -= 1;
upload.events.onCompleted(event.target.responseText);
// Check if there are any uploads left in a queue:
if (manager.uploadsQueue.length) {
manager.ajaxUpload(manager.uploadsQueue.shift());
}
};
// Triggered when upload fails:
xhr.onerror = function () {
console.log('Upload failed: ', upload.fileName);
};
// Append additional data if provided:
if (data) {
for (prop in data) {
if (data.hasOwnProperty(prop)) {
console.log('Adding data: ' + prop + ' = ' + data[prop]);
formData.append(prop, data[prop]);
}
}
}
// Append file data:
formData.append(key, file);
// Initiate upload:
xhr.send(formData);
},
on: function (element, eventName, handler) {
if (!element) {
return;
}
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + eventName, handler);
} else {
element['on' + eventName] = handler;
}
}
};
module.fileApiSupported = function () {
if (typeof supportsFileApi !== 'boolean') {
var input = document.createElement("input");
input.setAttribute("type", "file");
supportsFileApi = !!input.files;
}
return supportsFileApi;
};
module.initialize = function (options) {
return new UploadManager(options);
};
return module;
});
and then i could call the function from outside :
$("#testcontrol").click(function(){
console.log( "it's clicked !" );
monmanager.ajaxUpload(monupload);
});
now it's fine :)

db value becomes null or even on indexdb open it does not go into onsuccess or upgradeneeded functions

(function () {
var db;
function openDB(dbname, dbtable, keypath) {
var version = 1;
// open the database
var indexeddb_request = indexedDB.open( dbname, version ); // connect + open database
// if error
indexeddb_request.onerror = function ( event ) {
console.log( event.target );
console.trace();
}
// if success
indexeddb_request.onsuccess = function ( event ) {
console.log( event.target );
console.trace();
db = event.target.result;
}
// if onupgradeneeded
indexeddb_request.onupgradeneeded = function( event ) {
console.log( event.target );
console.trace();
db = event.target.result;
var objectStore = db.createObjectStore( dbtable, { keyPath: 'url' } );
}
}
function getObjectStore(store_name, mode) {
var tx = db.transaction(store_name, mode);
return tx.objectStore(store_name);
}
function addPublication(dbtable, data) {
console.log("addPublication arguments:", arguments);
var store = getObjectStore(dbtable, 'readwrite');
var req;
try {
for (var i in data) {
req = store.add(data[i]);
}
//req = store.add(data);
} catch (e) {
if (e.name == 'DataCloneError')
displayActionFailure("This engine doesn't know how to clone a Blob, " +
"use Firefox");
throw e;
}
req.onsuccess = function (evt) {
console.log("Insertion in DB successful");
};
req.onerror = function() {
console.error("addPublication error", this.error);
};
}
function displayPubList(store, store_name) {
console.log("displayPubList");
if (typeof store == 'undefined')
store = getObjectStore(store_name, 'readonly');
var req;
req = store.count();
// Requests are executed in the order in which they were made against the
// transaction, and their results are returned in the same order.
// Thus the count text below will be displayed before the actual pub list
// (not that it is algorithmically important in this case).
req.onsuccess = function(evt) {
console.log("Count of records " + evt.target.result +
' record(s) in the object store.');
};
req.onerror = function(evt) {
console.error("add error", this.error);
};
var i = 0;
req = store.openCursor();
req.onsuccess = function(evt) {
var cursor = evt.target.result;
// If the cursor is pointing at something, ask for the data
if (cursor) {
console.log("displayPubList cursor:", cursor);
req = store.get(cursor.key);
req.onsuccess = function (evt) {
var value = evt.target.result;
console.log("Key :" + cursor.key + 'value :' + value.ssn );
};
// Move on to the next object in store
cursor.continue();
// This counter serves only to create distinct ids
i++;
} else {
console.log("No more entries");
}
};
}
openDB("abc","names","ssn");
const customerData = [
{ ssn: "444-44-4444", name: "Bill", age: 35, email: "bill#company.com" },
{ ssn: "555-55-5555", name: "Donna", age: 32, email: "donna#home.org" }
];
addPublication("names",customerData);
displayPubList("abc","names");
})();
I'm trying to test the above code from chrome developer tools. But looks like some cases the call goes into sucess or upgradeneeded. And many times its always null. Please let me know if i'm doing something wrong here.

chrome extension download files

I'm writing a js extension for chrome that should download multiple created files.
the problem is that chrome auto opens the file in the current tab at the following address:
filesystem:https://stackoverflow.com//temporary/myfile.ini
and second if I cycle on an array made this way
fileini = [ ["filename",file-content], [], ... ] it just print the last one
and if I try to cycle on it using a setTimeout I get an error from the console
below I post the code
function createDataFile(filename, content) {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 1024 * 1024 * 20, function(fs) {
fs.root.getFile(filename, {
create : true
}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var blob = new Blob(content);
console.log("5");
fileWriter.addEventListener("writeend", function() {
// navigate to file, will download
location.href = fileEntry.toURL();
}, false);
fileWriter.write(blob);
}, function() {
});
}, function() {
});
}, errorHandler);
}
function errorHandler(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
console.log('Error: ' + msg);
}
createFileCycle();
function prnt(x) {
var y;
if (fileini[x] !== undefined) {
createDataFile(fileini[x][0], objToArray(fileini[x][1]));
y = x - 1;
console.log("printed file" + x);
} else {
y = x - 1;
}
if (x > 0)
return setTimeout(function() {
console.log("going to print file " + y);
prnt(y);
}, 500);
else
return 0;
}
prnt(fileini.length - 1);
}
function createFileCycle() creates fileini array as explained above
I hope someone could help me.
btw months ago on an old notebook running ubuntu 32bit I had it working, now on windows 7 it doesn't work and I cannot get around the problem.

QUOTA_EXCEEDED_ERR in Chrome FileSystem API

In Chrome23/Mac OS 10.8.2 this fiddle logs an error, and I want to know why.
Surprisingly enough, error does not occur if I put a breakpoint on the line that says '// BREAKPOINT' and simply resume execution.
Is it possible for JS to exceed some call rate limit in Chrome? I couldn't think of a better explanation.
Full code (I am using lodash, see its documentation of _.bind and _.bindAll):
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.LocalFileSystem = window.LocalFileSystem || {PERSISTENT: window.PERSISTENT};
fs = {
initFS: function() {
window.requestFileSystem(LocalFileSystem.PERSISTENT,
1024 * 1024, this.gotFS, this.fail);
},
fail: function(source, err) {
err.source = source;
var msg = '';
switch (err.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
err.msg = msg;
console.log('err ', JSON.stringify(err));
},
failarg: function(msg) {
return _.bind(this.fail, this, msg);
},
gotFS: function(fs) {
this.fs = this.fs || fs;
this.readConfig();
this.listApps(fs.root); // BREAKPOINT
},
listApps: function(fsroot) {
this.rootReader = this.rootReader || fsroot.createReader();
this.rootReader.readEntries(this.gotRootEntries, this.fail);
},
gotRootEntries: function(entries) {
_(entries).forEach(function(entry) {
if (entry.isDirectory && this.controller) {
// TODO
}
});
},
readConfig: function() {
this.fs.root.getFile('config.json', {create:true}, this.gotConfigFileEntry, this.failarg('getFile'));
},
gotConfigFileEntry: function(entry) {
entry.file(this.gotConfigFile, this.failarg('entry.file'));
},
gotConfigFile: function(file) {
this.configFile = file;
var reader = new FileReader();
reader.onloaded = function(evt) {
if (evt.target.result) {
this.config = JSON.parse(evt.target.result);
}
};
reader.readAsText(this.configFile);
},
};
_.bindAll(fs);
$(function() {
fs.initFS();
});​
The following Fiddle, based on the original HTML 5 Rocks article (http://www.html5rocks.com/en/tutorials/file/filesystem/), demonstrates how to invoke the quota system.
http://jsfiddle.net/kim3er/h76qq/1/
window.webkitStorageInfo.requestQuota(PERSISTENT, 1024*1024, function(grantedBytes) {
//window.requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);
initFS(grantedBytes);
}, function(e) {
console.log('Error', e);
});

Categories

Resources