Javascript 使用HTML5 FileWriter覆盖文件

Javascript 使用HTML5 FileWriter覆盖文件,javascript,html,chromium,fileapi,Javascript,Html,Chromium,Fileapi,我正在使用保存我的Web应用程序的状态。我有一些JS定期调用FileWriter.write(因此,随着时间的推移,write方法会被多次调用)。默认情况下,FileWriter API使用“附加”方法来编写文件,这不符合我的需要,因为我不想覆盖文件内容 我第一次尝试这个: this._writer.seek(0); this._writer.write(content); this._writer.truncate(0); this._writer.write(content); 当您正在

我正在使用保存我的Web应用程序的状态。我有一些JS定期调用
FileWriter.write
(因此,随着时间的推移,
write
方法会被多次调用)。默认情况下,FileWriter API使用“附加”方法来编写文件,这不符合我的需要,因为我不想覆盖文件内容

我第一次尝试这个:

this._writer.seek(0);
this._writer.write(content);
this._writer.truncate(0);
this._writer.write(content);
当您正在编写比文件内容短的文本时,这不起作用。然后我试了一下:

this._writer.seek(0);
this._writer.write(content);
this._writer.truncate(0);
this._writer.write(content);
此代码本应清除文件,然后写入我的新内容,但调用
write
方法时出现以下错误:

Uncaught InvalidStateError: An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk.
奇怪的是:当我调试代码(使用断点)时,错误不会发生,就好像
FileWriter.truncate
是一种异步方法

我被困在这里了,有什么想法吗


我使用的是Chrome 30.0.1599.69

解决方案是以下代码:

this._writer.truncate(0);
window.setTimeout(function(){
    this._writer.write(content);
}.bind(this),500)

这只需等待500毫秒即可写入。不太好,但它可以工作…

这里有一个正确的代码,不会浪费500毫秒的等待时间

fileWriter.onwriteend = function() {
    if (fileWriter.length === 0) {
        //fileWriter has been reset, write file
        fileWriter.write(blob);
    } else {
        //file has been overwritten with blob
        //use callback or resolve promise
    }
};
fileWriter.truncate(0);

您可以截断并使用两个不同的
FileWriter
对象进行写入

fileEntry.createWriter(function (fileWriter) {

        fileWriter.truncate(0);

    }, errorHandler);

fileEntry.createWriter(function (fileWriter) {

        var blob = new Blob(["New text"], { type: 'text/plain' });

        fileWriter.write(blob);

    }, errorHandler);

如果要始终覆盖它,可以使用此方法

function save(path,data){
    window.resolveLocalFileSystemURL(dataDirectory, function(dir){
        dir.getFile(path, {create:true}, function(file){
            file.createWriter(function(fileWriter){
                fileWriter.seek(0);
                fileWriter.truncate(0);
                var blob = new Blob([data], {type:'text/plain'});
                fileWriter.write(blob);
            }, function(e){
                console.log(e);
            });
        });
    });
};

这是我在Chrome应用程序中使用syncFileSystem删除文件内容的最简单方法

两个createWriter,第一个截断,然后第二个重写为零(您可以使用新值进行更改):


你能详细说明一下吗?什么是“d”?@htulipe,这是我的jQuery。当截断和写入完成时,我在外部使用不同的对象来得到通知。您可以忽略它,也可以在写入时添加任何其他要执行的代码。@htulipe如果解决了问题,请将其标记为应答。检测到无限循环