2

I am creating an Ionic Application and I need to save data in a JSON file.

To create that file, I run:

this.file.writeFile(this.file.dataDirectory, 'test.json', 'hello,world,', {replace: true});

But the code above doesn't do anything. test.json doesn't get created!

What is the Issue?

EDIT: Someone told me I must use cordova. Is that true? If so, what does he mean?

EDIT: Is it because i can't file "this.file.dataDirectory"?

PS: I am using (ionic cordova run browser) to run the script. Would that cause problems.

Also, After using Melchia's example, I don't even get a console.log!

Ron Arel
  • 371
  • 1
  • 5
  • 14

2 Answers2

3

Run this command to install cordova file plugin:

$ ionic cordova plugin add cordova-plugin-file
$ npm install --save @ionic-native/file

After installing a plugin’s package, add it to your app’s NgModule.

import { File } from '@ionic-native/file';


...

@NgModule({
  ...

  providers: [
    ...
    File
    ...
  ]
  ...
})
export class AppModule { }

Then in your page.ts

import { File } from '@ionic-native/file';

constructor(private file: File) { }


this.file.writeFile(this.file.dataDirectory, 'test.json', 'hello,world,', {replace: true}).then(_ => console.log('Directory exists')).catch(err => console.log('Directory doesn\'t exist'));
Melchia
  • 22,578
  • 22
  • 103
  • 117
  • I have done all that just not the ".then(_ => console.log('Directory exists')).catch(err => console.log('Directory doesn\'t exist'));" part. I will make the changes and then update you. Thanks! – Ron Arel Jul 06 '18 at 18:38
  • Ok. I made the change and I don't get any console.log or does the json file get created. I don't know if this matters nut I am running with "ionic cordova run browser". @Melchia – Ron Arel Jul 06 '18 at 18:46
  • but did you test this in your device? – Melchia Jul 06 '18 at 18:53
  • Ofcourse it will not work in the browser because you're using cordova – Melchia Jul 06 '18 at 18:57
  • You can refer to this question https://stackoverflow.com/questions/13405129/javascript-create-and-save-file – Melchia Jul 06 '18 at 19:04
  • I did. 'this.download("test", "testing.txt", ".txt")' After taking the function you refered me to. Will this make a text file named testing.txt? @Melchia – Ron Arel Jul 06 '18 at 20:05
0

I think for ionic V4, you should use import { File } from '@ionic-native/file/ngx';

  • 1
    This doesn't seem to answer the original question, maybe you're trying to comment on the existing answer? It's better to put your comment under that answer, rather than as a whole new answer, or perhaps to suggest an edit to the existing answer with your new syntax, if you're certain it's correct. – DaveyDaveDave Feb 05 '19 at 10:27