0

I have the (adapted) following code:

    function saveFiles(saving_dir, content, name) {
      var i = 1;
      return new Promise(function(resolve) {
        chrome.fileSystem.getWritableEntry(saving_dir, function(entry) {
          entry.getFile(name, {
            create: true
          }, function(entry) {
            entry.createWriter(function(writer) {
              writer.onwrite = function() {
                writer.onwrite = null;
                writer.truncate(writer.position);
              };
              writer.onwriteend = function(e) {
                console.log(i)
                i++;
                console.log('written! "' + name + '"')
                // resolve();
              };
              writer.onerror = function(e) {
                console.log('failed! "' + name + '"');
                console.log(e);
              };

              var blob = new Blob([JSON.stringify(content)], {
                type: 'text/javascript'
              });
              writer.write(blob);
            }, function(e) {
              trace.innerText = 'error is ' + e;
              console.log(e);
            });
          });
        });
      });
    }

    saveFiles('/', 'hola', 'delete.txt');

And I don't know why this is executing the onwriteend event twice, with the console.log(i) giving 1 and 2.

If I add logs in between, everything is called once except the event. Any tip?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
GWorking
  • 4,011
  • 10
  • 49
  • 90
  • Possible duplicate of [Using the HTML5 FileWriter truncate() method?](http://stackoverflow.com/questions/6792607/using-the-html5-filewriter-truncate-method) – GWorking Sep 26 '16 at 13:28
  • I've seen this is a duplicated question of http://stackoverflow.com/questions/6792607/using-the-html5-filewriter-truncate-method, I've flagged it, but should I delete the question instead? – GWorking Sep 26 '16 at 13:28
  • I don't think this is an exact duplicate - this has a different _question_ regarding `onwriteend` specifically. – Xan Sep 26 '16 at 13:32

1 Answers1

1

You trigger a write, followed by truncate in onwrite listener.

Your call to truncate also triggers a writeend event, according to the last public draft of the spec.

Xan
  • 74,770
  • 16
  • 179
  • 206