How to write file into device persistent storage in Ionic 2?

Hi,

I’m trying to write JSON data into a file on device persistent storage. Here is what I did:

I installed "ionic-native": "^1.3.20", imported it to a file and declared cordova like the following:
import { File } from 'ionic-native'; declare var cordova: any; const fs:string = cordova.file.dataDirectory;

Then I was trying to write file like this:
File.writeFile(fs, 'user.json', JSON.stringify(data.json()), true) .then( _ => { console.log('yay'); } ) .catch( err => { console.log('boooh'); } )

When I tried ionic run browser, I’ve got the following error:
FileError is deprecated. Please use the 'name' or 'message' attributes of DOMError rather than 'code'. file.js:553 Uncaught TypeError: Cannot assign to read only property 'message' of object '#<FileError>' file.js:553

When I tried ionic run ios, the simulator gives me a blank page and Xcode doesn’t show any errors in the console.

When I tried ionic run android, it shows the app home screen, but won’t go into the page contains file writer code.

Any help would be appreciated.

1 Like

Is there a specific reason you are trying to create a file to store your JSON data ?

If not, you could use the HTML5 local storage, or if the data are actually sensitives, you could use the secure storage plugin.

You obviously need to stringify your data before storing it.

Hi @schankam , thanks for your reply.

I need to cache the JSON data of each view from server for offline usage, so HTML5 local storage won’t be enough as it has a very limited size. I could probably try SQLite, but It would be easier if I can save the JSON data as a file on device directly.

Since WEBSql is deprecated (or will be soon), and IndexDB is not working on iOS, I would suggest you to use the SQLite PLugin, which will give you much more advantages (you will actually be able to run some SQL query on your data), rather than depending on the FileSystem (which is probably also slower).

Schankam, is ionic-angular/SqlStorage to be deprecated? Or will SqlStorage adapt the SQLite plugin, maybe?