如何覆盖文件系统中的文件 API

How to overwrite file in FileSystem API

函数如下:

this.saveObj = function(o, finished)
{   
    root.getDirectory("object", {create: true}, function(directoryEntry)
    {
        directoryEntry.getFile("object.json", {create: true}, function(fileEntry) 
        {
            fileEntry.createWriter(function(fileWriter) 
            {

                fileWriter.onwriteend = function(e) 
                {
                    finished(fileEntry);
                };

                fileWriter.onerror = errorHandler;
                var blob = new Blob([JSON.stringify(o)], {type: "json"});

                fileWriter.write(blob);
            }, errorHandler);
        }, errorHandler);
    }, errorHandler);
};

现在当我保存对象时一切正常。假设我保存 {"id":1},我的文件内容将是 {"id":1}。现在我用 o = {}; 编辑对象并再次保存,我的文件内容突然变成了 {} "id":1 }.

它只是覆盖旧内容,但不清除它。我是否必须在写入文件之前删除该文件,还是我遗漏了什么?

据我了解,write 方法会将提供的内容写入某个位置。对我来说,这意味着除非您覆盖部分内容,否则现有内容不会受到影响。所以我要说是,删除文件并保存一个新文件。

source

根据仅使用 { create: true} 的 Mozilla 文档:

The existing file or directory is removed and replaced with a new one, then the successCallback is called with a FileSystemFileEntry or a FileSystemDirectoryEntry, as appropriate.

在Chrome72测试过,好像是这样。

这不起作用,因为文件似乎是持久的。该文件将被覆盖(第一个字节)但大小将保持不变。所以这至少是 Chrome 72.

中的错误

Source