1var fs = require('fs');
2
3var myOptions = {
4 name: 'Avian',
5 dessert: 'cake'
6 flavor: 'chocolate',
7 beverage: 'coffee'
8};
9
10var data = JSON.stringify(myOptions);
11
12fs.writeFile('./config.json', data, function (err) {
13 if (err) {
14 console.log('There has been an error saving your configuration data.');
15 console.log(err.message);
16 return;
17 }
18 console.log('Configuration saved successfully.')
19});
1const fs = require('fs');
2
3let obj = {
4 table: []
5};
6
7fs.exists('myjsonfile.json', function(exists) {
8
9 if (exists) {
10
11 fs.readFile('myjsonfile.json', function readFileCallback(err, data) {
12
13 if (err) {
14 console.log(err);
15 } else {
16 obj = JSON.parse(data);
17
18 //Data that you want add to the file
19 for (i = 0; i < 5; i++) {
20 obj.table.push({
21 id: i,
22 square: i * i
23 });
24 }
25
26 let json = JSON.stringify(obj);
27 fs.writeFile('myjsonfile.json', json);
28 }
29 });
30 } else {
31
32 console.log("file not exists");
33
34 //Data that you want add to the file
35 for (i = 0; i < 5; i++) {
36 obj.table.push({
37 id: i,
38 square: i * i
39 });
40 }
41
42 let json = JSON.stringify(obj);
43 fs.writeFile('myjsonfile.json', json);
44 }
45});