overwrite a file with HTML5 FileWriter

前端 未结 5 546
我寻月下人不归
我寻月下人不归 2021-01-01 22:30

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

相关标签:
5条回答
  • 2021-01-01 22:44

    This is the simplest way how i use to delete the content of a file with syncFileSystem in my Chrome App.

    Two createWriter, the first one truncates then the second one overwrites with nothing (you can change with your new value) :

    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);
    
    });
    
    0 讨论(0)
  • 2021-01-01 22:50

    A workaround is the following code:

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

    This simply wait 500 milliseconds before writing. Not great but it works...

    0 讨论(0)
  • 2021-01-01 22:59

    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);
    
    0 讨论(0)
  • 2021-01-01 22:59

    If you want to always override it, you can use this method

    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);
                });
            });
        });
    };
    
    0 讨论(0)
  • 2021-01-01 23:01

    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);
    
    0 讨论(0)
提交回复
热议问题