Cordova - File System

There are times when you have to use or manipulate file system manager through the app. You can integrate the file system into your app using the file System plugin in apache Cordova.

This plugin is used for manipulating native file system on the user's also involves the similar steps as in the case with the previous plungins.

Step 1 – Install the File Plugin

To install this plugin, open command prompt and run the piece of code below:

C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-file

Step 2 - Adding Buttons

Now, you have to add four buttons in index.html  to create file, write to file, read it and delete it. Also, I have added an extra button textarea where content of our file will be shown.

<button id = "creatingFile">CREATE FILE</button>

<button id = "writingFile">WRITE FILE</button>
<button id = "readingFile">READ FILE</button>
<button id = "removingFile">DELETE FILE</button>
<textarea id = "textarea"></textarea>


Step 3 - Adding Event Listeners

You will add event listeners in index.js inside onDeviceReady function to make sure that everything has started before the plugin is used.

document.getElementById("createFile").addEventListener("click", creatingFile);

document.getElementById("writeFile").addEventListener("click", writingFile);
document.getElementById("readFile").addEventListener("click", readingFile);
document.getElementById("removeFile").addEventListener("click", removingFile);


Step 4A - Create File function

On the device, the file will be created in root folder of the app. You need to grant superuser access to your folders to be able to access root folder. In this case the path to root folder is \data\data\com.example.newapp\cache. At present, this folder is empty.

Cordova - File System

Now, you have to add function that will create the log.txt file. You will write this code in index.js file.

We are first requesting the file system. This method uses four parameters type, it can be WINDOW.TEMPORARY or WINDOW.PERSISTENT.

Size is value in bytes that will be required for storage (5MB in this case).

function creatingFile() {

   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 when you will press CREATE FILE button the alert will confirm that the file created successfully. 

Last updated:3/19/2018 2:11:23 AM
Anonymous User

Anonymous User

I am a content writter !


Leave Comment