Javascript – overwrite a file with HTML5 FileWriter

chromiumfileapihtmljavascript

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.

I first tried this:

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

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.

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?

I am using Chrome 30.0.1599.69

Best Answer

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