我正在尝试将文本附加到文件中。
我按照插件的 github 页面的建议遵循了Html5rocks教程。
我已经成功地创建了一个文件并写入了它。但是当我尝试附加文本时,我得到了一个写入成功事件,但没有添加任何文本。我只能更改字符,但最后没有添加字符。这不是异步问题,我也在尝试使用 chrome 的 js 控制台进行实时测试。我也在fileWriter.seek(fileWriter.length)
尝试最后写之前使用。(但 seek(0) 写一个开头)
有我写的模块:
'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;
}
我将它与 chrome 控制台一起使用
var f = new File_mgmt("test");
f.writeTextBlob("test1");
f.writeTextBlob("test2");
编辑
我试图通过 awindow.requestFileSystem()
来追加,但它仍然不起作用,我还更新了我的代码。
现在我在做
var f = new File_mgmt("test");
f.testWrite("test1");
f.testWrite("test2");