ionic-framework icon indicating copy to clipboard operation
ionic-framework copied to clipboard

FileWriter Broken in Ionic 2.0.0-beta.1

Open marcus-robinson opened this issue 10 years ago • 17 comments

Short description of the problem:

FileWriter fails silently when you try to write a file in Ionic 2. Ionic throws no error, but the file is never written and the onwriteend / onerror handlers are never called. I have tested the same code on Ionic v1 and it works fine, so it appears to be a v2 specific issue. Have only tested Android, but could be iOS issue too.

What behavior are you expecting?

I expect the file to be written and the onwriteend handler called, or if there's an error, I expect the onerror handler to be called.

Steps to reproduce:

  1. Create a new Ionic 2.0.0-beta.1 project and install the latest cordova by running: npm update -g cordova ionic@beta
  2. Add Android platform by running: ionic platform android
  3. Install latest Cordova File plugin (4.1.1) by running: cordova plugin add cordova-plugin-file
  4. Add the below code snippet [0] to your App.js and call this.initializeApp() from your App constructor
  5. Deploy to your android device using: ionic run android
  6. Observe that the FileWriter handlers are never called and the file written to the device is an empty 0 byte file.

CODE SNIPPET [0] :

  initializeApp() {
    this.platform.ready().then(() => {

      this.cordovaFileError = {
        1: 'NOT_FOUND_ERR',
        2: 'SECURITY_ERR',
        3: 'ABORT_ERR',
        4: 'NOT_READABLE_ERR',
        5: 'ENCODING_ERR',
        6: 'NO_MODIFICATION_ALLOWED_ERR',
        7: 'INVALID_STATE_ERR',
        8: 'SYNTAX_ERR',
        9: 'INVALID_MODIFICATION_ERR',
        10: 'QUOTA_EXCEEDED_ERR',
        11: 'TYPE_MISMATCH_ERR',
        12: 'PATH_EXISTS_ERR'
      };

      var dir = "";
      if (this.platform.is('ios')) {
        //documentsDirectory is specific IOS.
        dir = cordova.file.documentsDirectory;
      }
      else if (this.platform.is('android')) {
        //cordova.file.dataDirectory or cordova.file.externalDataDirectory is specific to Android
        dir = cordova.file.dataDirectory;
      }      

      var fileName = "myTestFile.txt";
      var path = "myTestDir";
      this.createDir(dir, path, false).then(()=> {

        var options = {
          create: true,
          exclusive: true
        };

        try {
          console.log("we are trying to get filesystem with path " + dir + path);
          window.resolveLocalFileSystemURL(dir + path, (fileSystem)=> {
            console.log("Got it. Now we are trying to get file ", fileName, "at that path");
            fileSystem.getFile(fileName, options, (fileEntry)=> {
              console.log("Got the file. Now lets write to it.")
              fileEntry.createWriter((writer)=> {
                console.log("created a writer for the file path.");
                writer.onwriteend = function (evt) {
                  console.log('EXPECTED BEHAVIOUR: Write completed.');
                  if (this.error) {
                    console.error(this.error);
                  } else {
                    console.log("success!", evt);
                  }
                };

                writer.onerror = function(e) {
                  console.log('Write failed: ' + e.toString());
                  console.error(e);
                };

                console.log("Start writing of blob");

                var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});      
                writer.write(blob);

                console.log("ACTUAL BEHAVIOUR - writer fails silently and the handlers are never called.");

              });
            }, (error)=> {
              error.message = this.cordovaFileError[error.code];
              console.error(error);
            });
          }, (err)=> {
            err.message = this.cordovaFileError[err.code];
            console.error(err);
          });
        } catch (e) {
          e.message = this.cordovaFileError[e.code];
          console.error(e);
        }
      }, (error)=> {
        error.message = this.cordovaFileError[error.code];
        console.warn(error);
      });      


    });
  }


  createDir (path, dirName, replaceBool) {
    return new Promise((resolve, reject) => {

      if ((/^\//.test(dirName))) {
        reject('directory cannot start with \/');
      }

      var options = {
        create: true,
        exclusive: replaceBool
      };

      try {
        window.resolveLocalFileSystemURL(path, (fileSystem)=> {
          fileSystem.getDirectory(dirName, options, (result)=> {
            resolve(result);
          }, (error)=> {
            error.message = this.cordovaFileError[error.code];
            reject(error);
          });
        }, (err)=> {
          err.message = this.cordovaFileError[err.code];
          reject(err);
        });
      } catch (e) {
        e.message = this.cordovaFileError[e.code];
        reject(e);
      }

    });
  }  

Ionic Version: 2.0.0-beta.1

Browser & Operating System: iOS / Android / Chrome Tested on Genymotion Google Nexus 7. The above code works fine running on the same device using Ionic v1.

Run ionic info from terminal/cmd prompt:

Cordova CLI: 6.0.0
Gulp version:  CLI version 3.9.0
Gulp local:
Ionic Version: 2.0.0-beta.1
Ionic CLI Version: 2.0.0-beta.17
Ionic App Lib Version: 2.0.0-beta.8
OS: Win10
Node Version: v4.2.3

marcus-robinson avatar Feb 28 '16 06:02 marcus-robinson

Thanks for the issue, I'm curious how Ionic 2 would have any effect on the plugin. Is there a simpler case you can put together that highlights the issue? Perhaps one specific Cordova call that is failing, thanks!

tlancina avatar Mar 02 '16 00:03 tlancina

Hi Tim,

Here is a simpler case that highlights the issue:

var logOb = null;
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(dir) {    
    dir.getFile("log.txt", {create:true}, function(file) {        
        logOb = file;        
        var log = ":: TEST LOG ::" + " [" + (new Date()) + "]\n";        
        logOb.createWriter(function(fileWriter) {            
            fileWriter.seek(fileWriter.length);            
            var blob = new Blob([log], {type:'text/plain'});
            fileWriter.write(blob);            
        }, function(e){console.error(e);});         
    });
});

This code writes a 57 byte file on Ionic v1, but on Ionic v2 it just leaves an empty 0 byte file (using the same Cordova library version and using same Genymotion Android device).

I've debugged line-by-line and the issue stems from the fact that the "onload" handler on line 109 in Cordova's FileWriter.js is called when using Ionic v1, but is never called when using Ionic v2. See screenshot - this breakpoint is only ever hit when using Ionic v1:

filewriter write

Please let me know if you need any more information.

marcus-robinson avatar Mar 02 '16 21:03 marcus-robinson

Here is a screenshot of the device file system, where you can see the Ionic v1 app has a 57 byte file written and the ionic v2 app has a 0 byte file written:

log-file-sizes

marcus-robinson avatar Mar 02 '16 21:03 marcus-robinson

I have the same issue @ionic-framework beta 2. The Plugin creates the file, but does not write in it.

sghoe avatar Mar 29 '16 06:03 sghoe

Please note that I can only replicate this issue on Android. iOS does not seem to have this problem.

marcus-robinson avatar Mar 29 '16 06:03 marcus-robinson

Hey is this still an issue? It's working for me on a nexus 4 running 4.4.4: image

Steps I took: npm install -g ionic@beta [email protected] ionic start myapp --v2 --ts && cd myapp This is my constructor in app.ts:

  constructor(platform: Platform) {
    platform.ready().then(() => {
      window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(dir) {
        dir.getFile("log.txt", {create:true}, function(file) {
            var logOb = file;        
            var log = ":: TEST LOG ::" + " [" + (new Date()) + "]\n";
            logOb.createWriter(function(fileWriter) {
                fileWriter.seek(fileWriter.length);
                var blob = new Blob([log], {type:'text/plain'});
                fileWriter.write(blob);
            }, function(e){console.error(e);});
        });
      });
    });
  }

cordova platform add android cordova plugin add cordova-plugin-file ionic run android -l adb shell adb run-as com.ionicframework.myapp571196 (id from config.xml) cd files && ls && cat log.txt

tlancina avatar Apr 01 '16 17:04 tlancina

Hey tlancina, working now with starter on my Samsung Galaxy Note 2. I will try to do the same way on my existing project. Thank you

My Visual Studio Code takes automaticly a false Version of FileSystem.d.ts, there is no window.resolveLocalFileSystemURL

sghoe avatar Apr 07 '16 11:04 sghoe

I have upgraded to the latest Ionic (Beta 4), but the issue is still occurring on Genymotion emulating Nexus 7 - 5.1.0 - API 22. Perhaps it's a Genymotion-specific issue.

marcus-robinson avatar Apr 10 '16 10:04 marcus-robinson

Hey guys! I have also tested this issue with a Nexus 7 running Android 6.0.1 and it seems to be working for me too. @marcus-robinson have you gotten a chance to try this on an actual device and not a Genymotion emulator?

jgw96 avatar Apr 11 '16 14:04 jgw96

Hey guys as it has been a little while since there was any activity on this issue i will be closing for now! Feel free to comment back if your still having the issue and ill gladly reopen (:

jgw96 avatar Apr 15 '16 21:04 jgw96

Hi, could you give me a sample code how to use cordova.file.xxx ? Even after add cordova-plugin-file into ionic 2 project, I still cannot use cordova.file.xxx. The variable cordova is not recognized, so I wonder how to declare and use it in my project... Thanks.

lhviet avatar Jul 08 '16 01:07 lhviet

Hello, i can't use window.resolveLocalFileSystemURL because it always error Error TS1128: Declara tion or statement expected, please help

vuhung3990 avatar Aug 03 '16 07:08 vuhung3990

@vuhung3990 @lhviet you can now you Ionic Native for all your file operations; http://ionicframework.com/docs/v2/native/file/

You shouldn't need to use any of the low level APIs directly.

marcus-robinson avatar Aug 03 '16 22:08 marcus-robinson

@marcus-robinson thanks for your suggest, i did try this but some functions not working. see my answer here: https://forum.ionicframework.com/t/cordova-file-plugin-not-working/44221/6

vuhung3990 avatar Aug 04 '16 03:08 vuhung3990

The same for me and I don't know how to store image data without this feature, it's very bad for me

All it's fine on iOS

akanass avatar Aug 23 '16 16:08 akanass

Same problem for me, I don't know if this is a ionic2 issue or crosswalk, because I detected that without crosswalk plugin the function writeFile() works perfectly. @jgw96 I opened an issue to crosswalk plugin but I'd like to reopen this issue here because it's not working.

https://github.com/crosswalk-project/cordova-plugin-crosswalk-webview/issues/143

omgalbert avatar Jun 10 '17 13:06 omgalbert

Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Ionic, please create a new issue and ensure the template is fully filled out.

ionitron-bot[bot] avatar Sep 02 '18 17:09 ionitron-bot[bot]