GWorking
GWorking

Reputation: 4341

Chrome app, Javascript, fileSystem -> createWriter -> onwriteend is called twice instead of one time (?)

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?

Upvotes: 0

Views: 329

Answers (1)

Xan
Xan

Reputation: 77523

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.

Upvotes: 1

Related Questions