2013-10-17 126 views
13

我使用HTML5 FileWriter API来保存我的web应用程序的状态。我有点JS定期调用FileWriter.write这样做(所以,随着时间的推移,write方法被称为几次)。默认情况下,FileWriter API使用'append'方法来编写不适合我需求的文件,因为我不想覆盖文件内容。用HTML5 FileWriter覆盖文件

我第一次尝试这样的:

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

回答

20

这里是不会在等待

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); 
+1

你能否详细说明?什么是“d”? – htulipe

+1

@htulipe,这是我在外部使用的jQuery.Deffered对象,在截断和写入完成时都会收到通知。写作完成后,您可以忽略它或添加任何其他想要执行的代码。 –

+0

@htulipe如果它解决了问题,请将其标记为答案。 –

1

一种解决方法是如下代码:

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

这只是在写之前等待500毫秒。不是很大,但它的工作原理...

3

可以截断,然后用两个不同的FileWriter对象写浪费500ms的一个正确的代码。

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); 
+0

其工作感谢 – Sajan

1

如果你想永远覆盖它,您可以使用此方法

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); 
      }); 
     }); 
    }); 
}; 
1

这是我如何使用删除与syncFileSystem文件的内容在我的Chrome应用最简单的方法。

两个createWriter,第一个截断,然后什么也没有第二个覆盖(你可以用新的值更改):

file.createWriter((fileWriter)=>fileWriter.truncate(0)); 

file.createWriter((fileWriter)=> { 

    fileWriter.onwriteend = function() { 
    console.log('New Actions!'); 
    }; 

    var blob = new Blob([''], {type: 'text/plain'}); 
    fileWriter.write(blob); 

});