Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overwrite a file with HTML5 FileWriter

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

like image 372
htulipe Avatar asked Oct 17 '13 12:10

htulipe


2 Answers

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);
like image 135
Ivan Nikitin Avatar answered Nov 13 '22 05:11

Ivan Nikitin


You can truncate and then write with two different FileWriter objects.

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);
like image 40
okh Avatar answered Nov 13 '22 07:11

okh