Skip to content

Cordova - File System

The cordova-plugin-file allows your application to read from and write to the device’s file system. This is essential for tasks like saving user-generated content, caching data, or managing application resources offline.

Note: Direct file system access comes with platform-specific paths and permissions. The plugin abstracts many of these complexities, providing standard directory locations.

Add the plugin to your project using the terminal or command prompt:

cordova plugin add cordova-plugin-file

Step 2 - UI Elements for File Operations (Example)

Section titled “Step 2 - UI Elements for File Operations (Example)”

In index.html, we’ll add buttons for common file operations and a textarea to display file content.

<!-- In index.html -->
<button id="createAppFileButton">Create File</button>
<button id="writeFileButton">Write to File</button>
<button id="readFileButton">Read File</button>
<button id="removeFileButton">Delete File</button>
<br><br>
<textarea id="fileContentArea" rows="5" cols="40" placeholder="File content will appear here..."></textarea>

Set up event listeners in index.js after the deviceready event.

// In index.js, after 'deviceready'
document.addEventListener('deviceready', () => {
document.getElementById("createAppFileButton").addEventListener("click", createAppFile);
document.getElementById("writeFileButton").addEventListener("click", writeToFile);
document.getElementById("readFileButton").addEventListener("click", readAppFile);
document.getElementById("removeFileButton").addEventListener("click", removeAppFile);
// Initialize file system access details on device ready
console.log('cordova.file.dataDirectory: ' + cordova.file.dataDirectory);
console.log('cordova.file.cacheDirectory: ' + cordova.file.cacheDirectory);
}, false);

The cordova-plugin-file provides several predefined directory paths (e.g., cordova.file.dataDirectory, cordova.file.cacheDirectory). We will use cordova.file.dataDirectory for persistent app-specific files.

Step 4 - Implementing File Operation Functions

Section titled “Step 4 - Implementing File Operation Functions”

The core of file operations involves getting a DirectoryEntry for a chosen directory, then using its methods to get or create FileEntry objects, and subsequently FileWriter or FileReader objects.

This function creates a new, empty file named mylog.txt in the application’s data directory.

const fileName = "mylog.txt";
function createAppFile() {
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) {
console.log('File system resolved: ' + dirEntry.name);
dirEntry.getFile(fileName, { create: true, exclusive: true }, function (fileEntry) {
console.log(fileName + ' created successfully at: ' + fileEntry.toURL());
alert('File created: ' + fileName);
}, onErrorCreateFile);
}, onErrorResolveFS);
}
function onErrorCreateFile(error) {
console.error('Error creating file: ' + error.code);
if (error.code === FileError.PATH_EXISTS_ERR || error.code === 12) { // PATH_EXISTS_ERR is 12
alert('File already exists.');
} else {
alert('Error creating file: ' + error.code);
}
}
function onErrorResolveFS(error) {
console.error('Error resolving file system: ' + error.code);
alert('Error resolving file system: ' + error.code);
}

When CREATE FILE is pressed, if mylog.txt doesn’t exist, it will be created. An alert confirms success or indicates if the file already exists (due to exclusive: true).

This function writes text content to mylog.txt. If the file doesn’t exist, it will be created.

function writeToFile() {
const textToWrite = "Hello World! Writing to file at " + new Date().toLocaleTimeString();
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) {
dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log(fileName + ' write completed.');
alert('Content written to ' + fileName);
// Optionally, read and display content after writing
// readAppFile();
};
fileWriter.onerror = function (e) {
console.error('Write failed: ' + e.toString());
alert('Write failed: ' + e.toString());
};
const dataObj = new Blob([textToWrite], { type: 'text/plain' });
fileWriter.write(dataObj);
}, onErrorCreateWriter);
}, onErrorGetFile);
}, onErrorResolveFS);
}
function onErrorCreateWriter(error) {
console.error('Error creating file writer: ' + error.code);
alert('Error creating file writer: ' + error.code);
}
function onErrorGetFile(error) {
console.error('Error getting file: ' + error.code);
alert('Error getting file: ' + error.code);
}

Pressing WRITE TO FILE will write or overwrite mylog.txt with the sample text.

This function reads the content of mylog.txt and displays it in the textarea.

function readAppFile() {
window.resolveLocalFileSystemURL(cordova.file.dataDirectory + fileName, function (fileEntry) {
fileEntry.file(function (file) {
const reader = new FileReader();
reader.onloadend = function() {
console.log("Successful file read: " + this.result);
document.getElementById('fileContentArea').value = this.result;
alert('File content loaded.');
};
reader.onerror = function(e) {
console.error('Failed file read: ' + e.toString());
alert('Failed file read: ' + e.toString());
};
reader.readAsText(file);
}, onErrorReadFile);
}, onErrorResolveFileForRead);
}
function onErrorReadFile(error) {
console.error('Error reading file object: ' + error.code);
alert('Error reading file object: ' + error.code);
}
function onErrorResolveFileForRead(error) {
console.error('Error resolving file for reading: ' + error.code + '. Does the file exist?');
alert('Error resolving file: ' + error.code + '. Ensure file exists.');
document.getElementById('fileContentArea').value = 'File not found or unreadable.';
}

Clicking READ FILE will attempt to load and display the content of mylog.txt.

This function deletes mylog.txt from the application’s data directory.

function removeAppFile() {
window.resolveLocalFileSystemURL(cordova.file.dataDirectory + fileName, function (fileEntry) {
fileEntry.remove(function () {
console.log(fileName + ' removed successfully.');
alert('File removed: ' + fileName);
document.getElementById('fileContentArea').value = ''; // Clear textarea
}, onErrorRemoveFile);
}, onErrorResolveFileForRemove);
}
function onErrorRemoveFile(error) {
console.error('Error removing file: ' + error.code);
alert('Error removing file: ' + error.code);
}
function onErrorResolveFileForRemove(error) {
console.error('Error resolving file for removal: ' + error.code + '. Does the file exist?');
alert('Error resolving file for removal: ' + error.code + '. Ensure file exists.');
}

Pressing DELETE FILE will remove mylog.txt. Subsequent reads will fail until the file is recreated.

Consult the official cordova-plugin-file documentation for a complete API reference and details on platform quirks.