Joshua Moon
Joshua Moon

Reputation: 357

cordova-plugin-file clean overwrite of file

I'm looking for a clean and safe way to fully overwrite existing files when using the cordova-plugin-file Cordova plugin. What I've found, is that even when using the exclusive: false option, if the new file contents is shorter than the existing file, the remainder of the existing file persists at the end of the new file.

Example. I have an existing file with the contents of 0123456789, and want to replace it with abcd. When using exclusive: false, the file I end up with afterwards has the contents of abcd456789

Obviously this causes complications when reading back, especially when I expect these files to be correct json.

I've been unable to find other answers that don't just simply say use exclusive: false.

So far, I can work around this by manually deleting the file first, then writing to it, but this leaves me a point where I'm at risk of losing the entire file data if the app closes at the wrong moment.

Another option may be to write to a temp file, then remove the existing one, then copy the temp, then remove the temp. And when reading, check for the file I want, if it's not there, check for a temp file for it, then copy and clean up if exists. This feels like a very long-winded work around for something that should be an option.

Am I missing something here?

This is my existing work around, though it does not handle the potential of app closing yet. Is there a nicer way before I have to go down that rabbit hole?

  private replaceFileAtPath<T>(path: string, data: T): void {
    FileService.map.Settings.getFile(path, { create: true }, fileEntry => {
      fileEntry.remove(() => {})
      FileService.map.Settings.getFile(path, { create: true }, fe =>
        this.writeFile(fe, data)
      )
    })
  }

  private writeFile<T>(file: FileEntry, data: T, cb?: () => void): void {
    file.createWriter(writer => {
      const blob = new Blob([JSON.stringify(data)], { type: 'application/json' })

      writer.write(blob)
    })
  }

Upvotes: 1

Views: 648

Answers (1)

KeyAnyPress
KeyAnyPress

Reputation: 1

i guess i found the way to fix this.

You can use HTML5 FileWriter truncate() method.

    file.createWriter(writer => {
      const blob = new Blob([JSON.stringify(data)], { type: 'application/json' })
      const truncated = false;
      writer.onwriteend = function() {
        if (!truncated) {
          truncated = true;
          this.truncate(this.position);
          return;
        }
      };
      writer.write(blob)
    })

Upvotes: 0

Related Questions