Cordova: How to save text files with vanilla JS

227 Views Asked by At

I am going to turn an array into a text file to send to a different device. I have tried doing this using plugins and libraries, but that didn't seem to work for me. I was delighted to find this solution that does not use any plugins or libraries. Sadly it works in my browser, but doesn't seem to work when trying it in the app itself.

The code from the website:

const downloadToFile = (content, filename, contentType) => {
  const a = document.createElement('a');
  const file = new Blob([content], {type: contentType});
  
  a.href= URL.createObjectURL(file);
  a.download = filename;
  a.click();

    URL.revokeObjectURL(a.href);
};

document.querySelector('#btn2').addEventListener('click', () => {
  const textArea = 'This is the text that will be in the file'  
  downloadToFile(textArea, 'data.txt', 'text/plain');
});

Now I'm wondering is there a way to turn this into something that would work on android?

1

There are 1 best solutions below

1
On

On Android with cordova, assuming you are using an array (my_array) as source for your file

window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, function (dirEntry) {
        console.log('file system open: ' + dirEntry.name);
        var isAppend = false;
        createFile(dirEntry, nombreFichero, isAppend);
    }, onErrorLoadFs);

And then a function to create a file:

function createFile(dirEntry, fileName, isAppend) {

var array_file = my_array.join("\n");
dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {

    //writeFile(fileEntry, null, isAppend);
    writeFile(fileEntry, array_file, isAppend);

}, onErrorCreateFile);

And a function to write to file:

function writeFile(fileEntry, dataObj, isAppend) {
    fileEntry.createWriter(function (fileWriter) {

        fileWriter.onwriteend = function () {
            console.log("Successful file write..." + fileEntry.name);
        };

        fileWriter.onerror = function (e) {
            console.log("Failed file read: " + e.toString());
        };

        fileWriter.write(dataObj);
    });
}