Reputation: 1641
I am doing an app using ionic 3 and the file plugin, i am trying to write a json string to a json file under my assets folder which this hierarchy : -assets -> mock -> msg-list.json , with assets as the folder from the ionic files.
When using the file plugin :
this.file.writeExistingFile("file://android_asset/www/assets/mock/","msg-list.json",JSON.stringify(data))
.catch(
error => {
console.log(error);
}
);
I always get an error with the code 1000, which is the one for the bad url, i did remove a "/" after file: ( there has been 3 ) and still got the 1000 code error.
What should i do ?
Upvotes: 1
Views: 3522
Reputation: 7326
the application folder ( file://android_asset ) is read only so you could not write in this folder
read on the readme here https://github.com/apache/cordova-plugin-file
you can use applicationStorageDirecory
(this.file.applicaTionStorageDirecory)
which is /data/data/:app-id:, you are able to write there.
So your solution would be
First step.
copy the file msg-list.json
from the application's file assets/mock
to data storage file, when app is launched (add this in app.component.ts and on platform ready)
this.file.copyFile(this.file.applicationDirectory + '/www/assets/mock', 'msg-list.json', this.file.applicationStorageDirectory, 'msg-list.json').then(...)
Second step.
you can now read and write the file in the data storage everywhere in your app.
To write the file I suggest to use writeFile
function (not writeExistingFile
) because the writeExistingFile
function is just writeFile
with the option: {replace: true}
(see source code her) . And with writeFile function you can set the options you want.
export interface IWriteOptions {
replace?: boolean;
append?: boolean;
truncate?: number; // if present, number of bytes to truncate file to before writing
}
so for editing the file in data storage, I'd use like below:
this.file.writeFile(this.file.applicationStorageDirectory,"msg-list.json",JSON.stringify(data), {append: true}).then(...).catch(...)
Finally. always use data storage file.
NB:
use: this.file.applicationDirectory
instead of using directly file:///android_asset
and use this.file.applicationStorageDirectory
Upvotes: 7