用HTML5 FileWriter覆盖文件 [英] overwrite a file with HTML5 FileWriter
问题描述
我正在使用 HTML5 FileWriter API 保存我的webapp状态。我有一些JS定期调用 FileWriter.write
来做到这一点(所以,随着时间的推移,写
方法是多次打电话)。默认情况下,FileWriter API使用'append'方法来编写不符合我需要的文件,因为我不想覆盖文件内容。
I'm using HTML5 FileWriter API to save the state of my webapp. I have bit of JS that periodically calls FileWriter.write
to do that (so , over time, the write
method is called several times). By default FileWriter API use an 'append' approach to writing files which does not suits my needs since I wan't to overwrite the file content.
我首先尝试这样做:
this._writer.seek(0);
this._writer.write(content);
当您编写的文本短于文件内容时,这不起作用。然后我尝试了这个:
This is not working when you are writing a text shorter than the file content. I then tried this:
this._writer.truncate(0);
this._writer.write(content);
这段代码应该清除文件,然后写下我的新内容,但我得到以下内容调用 write
方法时出错:
This code is supposed to clear the file and then write my new content but I'm getting the following error when write
method is called:
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.
奇怪的是:当我调试代码(带断点)时,错误不会发生,因为if FileWriter.truncate
是一个异步方法......
Odd thing: when I debug the code (with a breakpoint), the error does not occur, as if FileWriter.truncate
was an asynchronous method...
我被困在这里,有什么想法吗?
I am stuck here, any ideas?
我使用的是Chrome 30.0.1599.69
I am using Chrome 30.0.1599.69
推荐答案
这是一个正确的代码,不会浪费500毫秒等待
Here is a correct code that won't waste 500ms on waiting
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);
这篇关于用HTML5 FileWriter覆盖文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!