Cordova - File System

This plugin is used for manipulating the native file system on the user's device.
We need to run the following code in the command prompt to install this plugin.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-file

In this example, we will show you how to create file, write to file, read it and delete it. For this reason, we will create four buttons in index.html. We will also add textarea wherein, the content of our file will be shown.
<button id = "createFile">CREATE FILE</button>
<button id = "writeFile">WRITE FILE</button>
<button id = "readFile">READ FILE</button>
<button id = "removeFile">DELETE FILE</button>
<textarea id = "textarea"></textarea>
We will add event listeners in index.js inside the onDeviceReady function to ensure that everything has started before the plugin is used.
document.getElementById("createFile").addEventListener("click", createFile);
document.getElementById("writeFile").addEventListener("click", writeFile);
document.getElementById("readFile").addEventListener("click", readFile);
document.getElementById("removeFile").addEventListener("click", removeFile);
The file will be created in the apps root folder on the device. To be able to access the root folder you need to provide superuser access to your folders. In our case, the path to root folder is \data\data\com.example.hello\cache. At the moment this folder is empty.
Let us now add a function that will create the log.txt file. We will write this code in index.js and send a request to the file system. This method uses WINDOW.TEMPORARY or WINDOW.PERSISTENT. The size that will be required for storage is valued in bytes (5MB in our case).
function createFile() {
   var type = window.TEMPORARY;
   var size = 5*1024*1024;
   window.requestFileSystem(type, size, successCallback, errorCallback)

   function successCallback(fs) {
      fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
         alert('File creation successfull!')
      }, errorCallback);
   }

   function errorCallback(error) {
      alert("ERROR: " + error.code)
   }
	
}
Now we can press the CREATE FILE button and the alert will confirm that we successfully created the file.
Now, we can check our apps root folder again and we can find our new file there.
In this step, we will write some text to our file. We will again send a request to the file system, and then create the file writer to be able to write Lorem Ipsum text that we assigned to the blob variable.
function writeFile() {
   var type = window.TEMPORARY;
   var size = 5*1024*1024;
   window.requestFileSystem(type, size, successCallback, errorCallback)

   function successCallback(fs) {
      fs.root.getFile('log.txt', {create: true}, function(fileEntry) {

         fileEntry.createWriter(function(fileWriter) {
            fileWriter.onwriteend = function(e) {
               alert('Write completed.');
            };

            fileWriter.onerror = function(e) {
               alert('Write failed: ' + e.toString());
            };

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

   function errorCallback(error) {
      alert("ERROR: " + error.code)
   }
}
After pressing the WRITE FILE button, the alert will inform us that the writing is successful as in the following screenshot.
Now we can open log.txt and see that Lorem Ipsum is written inside.
In this step, we will read the log.txt file and display it in the textarea element. We will send a request to the file system and get the file object, then we are creating reader. When the reader is loaded, we will assign the returned value to textarea.
function readFile() {
   var type = window.TEMPORARY;
   var size = 5*1024*1024;
   window.requestFileSystem(type, size, successCallback, errorCallback)

   function successCallback(fs) {
      fs.root.getFile('log.txt', {}, function(fileEntry) {

         fileEntry.file(function(file) {
            var reader = new FileReader();

            reader.onloadend = function(e) {
               var txtArea = document.getElementById('textarea');
               txtArea.value = this.result;
            };
            reader.readAsText(file);
         }, errorCallback);
      }, errorCallback);
   }

   function errorCallback(error) {
      alert("ERROR: " + error.code)
   }
}	
When we click the READ FILE button, the text from the file will be written inside textarea.
And finally we will create function for deleting log.txt file.
function removeFile() {
   var type = window.TEMPORARY;
   var size = 5*1024*1024;
   window.requestFileSystem(type, size, successCallback, errorCallback)

   function successCallback(fs) {
      fs.root.getFile('log.txt', {create: false}, function(fileEntry) {

         fileEntry.remove(function() {
            alert('File removed.');
         }, errorCallback);
      }, errorCallback);
   }

   function errorCallback(error) {
      alert("ERROR: " + error.code)
   }
}	
We can now press the DELETE FILE button to remove the file from the apps root folder. The alert will notify us that the delete operation is successful.
If we check the apps root folder, we will see that it is empty.

    45 Lectures 
     2 hours 

 Skillbakerystudios

    16 Lectures 
     1 hours 

 Nilay Mehta
 Print
 Add Notes
 Bookmark this page