Writing to JSON files

Hi, I’m trying to write to JSON files with my app and a promising method seems to be using node. However, to set it up the example I have is:
const fs = require(‘fs’);
fs.writeFile(‘message.txt’, ‘Hello Node.js’, (err) => {
if (err) throw err;
console.log(‘It’s saved!’);
});
I’m pretty sure I could just save it as message.json, but I can’t even declare the fs variable, VS code doesn’t recognise require(), and it gives me an error when I run it in ionic serve. Does anyone know how to use Node.js functions in ionic apps, or is there an easier way to write to JSON files?

File writing on mobile devices is restricted. Look at the Cordova File plugin (https://ionicframework.com/docs/v2/native/file/) as a method to do what you need.

1 Like

Additionally, browser environments do not have all the necessary infrastructure needed to run things that are expecting to be hosted in Node, so that’s a dead end.

1 Like

Thank you, I understand that know and I am trying to use Ionic Native. This is the code I’ve put in my main provider:
saveData(){
let file = {
fields: this.fields,
clients: this.clients,
links: this.links
};
let jFile = JSON.stringify(file);
console.log(file);
console.log(jFile);
File.writeFile(WHATEVER THE PATH IS, ‘sampleData.txt’, jFile, true);
}
What do I insert for the path? I can’t seem to find a value that works.

2 Likes

Read up on the actual plugin doc on the Cordova site. Varies from platform to platform. I think Ray Camden’s blog has some good examples

File.externalRootDirectory
worked for me and ended in the root of the device (not external SD :wink: )
I didn’t find the files at the deivce when used File.dataDirectory